content
stringlengths 228
999k
| pred_label
stringclasses 1
value | pred_score
float64 0.5
1
|
---|---|---|
blob: 82bbcc2b3bd321cf7c8770057555049f92f6dfba [file] [log] [blame]
// Copyright 2017 The Abseil Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "absl/base/internal/sysinfo.h"
#ifndef _WIN32
#include <sys/types.h>
#include <unistd.h>
#endif
#include <thread> // NOLINT(build/c++11)
#include <unordered_set>
#include <vector>
#include "gtest/gtest.h"
#include "absl/synchronization/barrier.h"
#include "absl/synchronization/mutex.h"
namespace absl {
namespace base_internal {
namespace {
TEST(SysinfoTest, NumCPUs) {
EXPECT_NE(NumCPUs(), 0)
<< "NumCPUs() should not have the default value of 0";
}
TEST(SysinfoTest, NominalCPUFrequency) {
#if !(defined(__aarch64__) && defined(__linux__)) && !defined(__EMSCRIPTEN__)
EXPECT_GE(NominalCPUFrequency(), 1000.0)
<< "NominalCPUFrequency() did not return a reasonable value";
#else
// Aarch64 cannot read the CPU frequency from sysfs, so we get back 1.0.
// Emscripten does not have a sysfs to read from at all.
EXPECT_EQ(NominalCPUFrequency(), 1.0)
<< "CPU frequency detection was fixed! Please update unittest.";
#endif
}
TEST(SysinfoTest, GetTID) {
EXPECT_EQ(GetTID(), GetTID()); // Basic compile and equality test.
#ifdef __native_client__
// Native Client has a race condition bug that leads to memory
// exaustion when repeatedly creating and joining threads.
// https://bugs.chromium.org/p/nativeclient/issues/detail?id=1027
return;
#endif
// Test that TIDs are unique to each thread.
// Uses a few loops to exercise implementations that reallocate IDs.
for (int i = 0; i < 32; ++i) {
constexpr int kNumThreads = 64;
Barrier all_threads_done(kNumThreads);
std::vector<std::thread> threads;
Mutex mutex;
std::unordered_set<pid_t> tids;
for (int j = 0; j < kNumThreads; ++j) {
threads.push_back(std::thread([&]() {
pid_t id = GetTID();
{
MutexLock lock(&mutex);
ASSERT_TRUE(tids.find(id) == tids.end());
tids.insert(id);
}
// We can't simply join the threads here. The threads need to
// be alive otherwise the TID might have been reallocated to
// another live thread.
all_threads_done.Block();
}));
}
for (auto& thread : threads) {
thread.join();
}
}
}
#ifdef __linux__
TEST(SysinfoTest, LinuxGetTID) {
// On Linux, for the main thread, GetTID()==getpid() is guaranteed by the API.
EXPECT_EQ(GetTID(), getpid());
}
#endif
} // namespace
} // namespace base_internal
} // namespace absl | __label__pos | 0.861588 |
Merge branch 'maint-1.7.3' into maint
[git/git.git] / builtin / checkout.c
1 #include "cache.h"
2 #include "builtin.h"
3 #include "parse-options.h"
4 #include "refs.h"
5 #include "commit.h"
6 #include "tree.h"
7 #include "tree-walk.h"
8 #include "cache-tree.h"
9 #include "unpack-trees.h"
10 #include "dir.h"
11 #include "run-command.h"
12 #include "merge-recursive.h"
13 #include "branch.h"
14 #include "diff.h"
15 #include "revision.h"
16 #include "remote.h"
17 #include "blob.h"
18 #include "xdiff-interface.h"
19 #include "ll-merge.h"
20 #include "resolve-undo.h"
21 #include "submodule.h"
22
23 static const char * const checkout_usage[] = {
24 "git checkout [options] <branch>",
25 "git checkout [options] [<branch>] -- <file>...",
26 NULL,
27 };
28
29 struct checkout_opts {
30 int quiet;
31 int merge;
32 int force;
33 int force_detach;
34 int writeout_stage;
35 int writeout_error;
36
37 /* not set by parse_options */
38 int branch_exists;
39
40 const char *new_branch;
41 const char *new_branch_force;
42 const char *new_orphan_branch;
43 int new_branch_log;
44 enum branch_track track;
45 struct diff_options diff_options;
46 };
47
48 static int post_checkout_hook(struct commit *old, struct commit *new,
49 int changed)
50 {
51 return run_hook(NULL, "post-checkout",
52 sha1_to_hex(old ? old->object.sha1 : null_sha1),
53 sha1_to_hex(new ? new->object.sha1 : null_sha1),
54 changed ? "1" : "0", NULL);
55 /* "new" can be NULL when checking out from the index before
56 a commit exists. */
57
58 }
59
60 static int update_some(const unsigned char *sha1, const char *base, int baselen,
61 const char *pathname, unsigned mode, int stage, void *context)
62 {
63 int len;
64 struct cache_entry *ce;
65
66 if (S_ISDIR(mode))
67 return READ_TREE_RECURSIVE;
68
69 len = baselen + strlen(pathname);
70 ce = xcalloc(1, cache_entry_size(len));
71 hashcpy(ce->sha1, sha1);
72 memcpy(ce->name, base, baselen);
73 memcpy(ce->name + baselen, pathname, len - baselen);
74 ce->ce_flags = create_ce_flags(len, 0) | CE_UPDATE;
75 ce->ce_mode = create_ce_mode(mode);
76 add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE);
77 return 0;
78 }
79
80 static int read_tree_some(struct tree *tree, const char **pathspec)
81 {
82 struct pathspec ps;
83 init_pathspec(&ps, pathspec);
84 read_tree_recursive(tree, "", 0, 0, &ps, update_some, NULL);
85 free_pathspec(&ps);
86
87 /* update the index with the given tree's info
88 * for all args, expanding wildcards, and exit
89 * with any non-zero return code.
90 */
91 return 0;
92 }
93
94 static int skip_same_name(struct cache_entry *ce, int pos)
95 {
96 while (++pos < active_nr &&
97 !strcmp(active_cache[pos]->name, ce->name))
98 ; /* skip */
99 return pos;
100 }
101
102 static int check_stage(int stage, struct cache_entry *ce, int pos)
103 {
104 while (pos < active_nr &&
105 !strcmp(active_cache[pos]->name, ce->name)) {
106 if (ce_stage(active_cache[pos]) == stage)
107 return 0;
108 pos++;
109 }
110 if (stage == 2)
111 return error(_("path '%s' does not have our version"), ce->name);
112 else
113 return error(_("path '%s' does not have their version"), ce->name);
114 }
115
116 static int check_all_stages(struct cache_entry *ce, int pos)
117 {
118 if (ce_stage(ce) != 1 ||
119 active_nr <= pos + 2 ||
120 strcmp(active_cache[pos+1]->name, ce->name) ||
121 ce_stage(active_cache[pos+1]) != 2 ||
122 strcmp(active_cache[pos+2]->name, ce->name) ||
123 ce_stage(active_cache[pos+2]) != 3)
124 return error(_("path '%s' does not have all three versions"),
125 ce->name);
126 return 0;
127 }
128
129 static int checkout_stage(int stage, struct cache_entry *ce, int pos,
130 struct checkout *state)
131 {
132 while (pos < active_nr &&
133 !strcmp(active_cache[pos]->name, ce->name)) {
134 if (ce_stage(active_cache[pos]) == stage)
135 return checkout_entry(active_cache[pos], state, NULL);
136 pos++;
137 }
138 if (stage == 2)
139 return error(_("path '%s' does not have our version"), ce->name);
140 else
141 return error(_("path '%s' does not have their version"), ce->name);
142 }
143
144 static int checkout_merged(int pos, struct checkout *state)
145 {
146 struct cache_entry *ce = active_cache[pos];
147 const char *path = ce->name;
148 mmfile_t ancestor, ours, theirs;
149 int status;
150 unsigned char sha1[20];
151 mmbuffer_t result_buf;
152
153 if (ce_stage(ce) != 1 ||
154 active_nr <= pos + 2 ||
155 strcmp(active_cache[pos+1]->name, path) ||
156 ce_stage(active_cache[pos+1]) != 2 ||
157 strcmp(active_cache[pos+2]->name, path) ||
158 ce_stage(active_cache[pos+2]) != 3)
159 return error(_("path '%s' does not have all 3 versions"), path);
160
161 read_mmblob(&ancestor, active_cache[pos]->sha1);
162 read_mmblob(&ours, active_cache[pos+1]->sha1);
163 read_mmblob(&theirs, active_cache[pos+2]->sha1);
164
165 /*
166 * NEEDSWORK: re-create conflicts from merges with
167 * merge.renormalize set, too
168 */
169 status = ll_merge(&result_buf, path, &ancestor, "base",
170 &ours, "ours", &theirs, "theirs", NULL);
171 free(ancestor.ptr);
172 free(ours.ptr);
173 free(theirs.ptr);
174 if (status < 0 || !result_buf.ptr) {
175 free(result_buf.ptr);
176 return error(_("path '%s': cannot merge"), path);
177 }
178
179 /*
180 * NEEDSWORK:
181 * There is absolutely no reason to write this as a blob object
182 * and create a phony cache entry just to leak. This hack is
183 * primarily to get to the write_entry() machinery that massages
184 * the contents to work-tree format and writes out which only
185 * allows it for a cache entry. The code in write_entry() needs
186 * to be refactored to allow us to feed a <buffer, size, mode>
187 * instead of a cache entry. Such a refactoring would help
188 * merge_recursive as well (it also writes the merge result to the
189 * object database even when it may contain conflicts).
190 */
191 if (write_sha1_file(result_buf.ptr, result_buf.size,
192 blob_type, sha1))
193 die(_("Unable to add merge result for '%s'"), path);
194 ce = make_cache_entry(create_ce_mode(active_cache[pos+1]->ce_mode),
195 sha1,
196 path, 2, 0);
197 if (!ce)
198 die(_("make_cache_entry failed for path '%s'"), path);
199 status = checkout_entry(ce, state, NULL);
200 return status;
201 }
202
203 static int checkout_paths(struct tree *source_tree, const char **pathspec,
204 const char *prefix, struct checkout_opts *opts)
205 {
206 int pos;
207 struct checkout state;
208 static char *ps_matched;
209 unsigned char rev[20];
210 int flag;
211 struct commit *head;
212 int errs = 0;
213 int stage = opts->writeout_stage;
214 int merge = opts->merge;
215 int newfd;
216 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
217
218 newfd = hold_locked_index(lock_file, 1);
219 if (read_cache_preload(pathspec) < 0)
220 return error(_("corrupt index file"));
221
222 if (source_tree)
223 read_tree_some(source_tree, pathspec);
224
225 for (pos = 0; pathspec[pos]; pos++)
226 ;
227 ps_matched = xcalloc(1, pos);
228
229 for (pos = 0; pos < active_nr; pos++) {
230 struct cache_entry *ce = active_cache[pos];
231 if (source_tree && !(ce->ce_flags & CE_UPDATE))
232 continue;
233 match_pathspec(pathspec, ce->name, ce_namelen(ce), 0, ps_matched);
234 }
235
236 if (report_path_error(ps_matched, pathspec, prefix))
237 return 1;
238
239 /* "checkout -m path" to recreate conflicted state */
240 if (opts->merge)
241 unmerge_cache(pathspec);
242
243 /* Any unmerged paths? */
244 for (pos = 0; pos < active_nr; pos++) {
245 struct cache_entry *ce = active_cache[pos];
246 if (match_pathspec(pathspec, ce->name, ce_namelen(ce), 0, NULL)) {
247 if (!ce_stage(ce))
248 continue;
249 if (opts->force) {
250 warning(_("path '%s' is unmerged"), ce->name);
251 } else if (stage) {
252 errs |= check_stage(stage, ce, pos);
253 } else if (opts->merge) {
254 errs |= check_all_stages(ce, pos);
255 } else {
256 errs = 1;
257 error(_("path '%s' is unmerged"), ce->name);
258 }
259 pos = skip_same_name(ce, pos) - 1;
260 }
261 }
262 if (errs)
263 return 1;
264
265 /* Now we are committed to check them out */
266 memset(&state, 0, sizeof(state));
267 state.force = 1;
268 state.refresh_cache = 1;
269 for (pos = 0; pos < active_nr; pos++) {
270 struct cache_entry *ce = active_cache[pos];
271 if (source_tree && !(ce->ce_flags & CE_UPDATE))
272 continue;
273 if (match_pathspec(pathspec, ce->name, ce_namelen(ce), 0, NULL)) {
274 if (!ce_stage(ce)) {
275 errs |= checkout_entry(ce, &state, NULL);
276 continue;
277 }
278 if (stage)
279 errs |= checkout_stage(stage, ce, pos, &state);
280 else if (merge)
281 errs |= checkout_merged(pos, &state);
282 pos = skip_same_name(ce, pos) - 1;
283 }
284 }
285
286 if (write_cache(newfd, active_cache, active_nr) ||
287 commit_locked_index(lock_file))
288 die(_("unable to write new index file"));
289
290 resolve_ref("HEAD", rev, 0, &flag);
291 head = lookup_commit_reference_gently(rev, 1);
292
293 errs |= post_checkout_hook(head, head, 0);
294 return errs;
295 }
296
297 static void show_local_changes(struct object *head, struct diff_options *opts)
298 {
299 struct rev_info rev;
300 /* I think we want full paths, even if we're in a subdirectory. */
301 init_revisions(&rev, NULL);
302 rev.diffopt.flags = opts->flags;
303 rev.diffopt.output_format |= DIFF_FORMAT_NAME_STATUS;
304 if (diff_setup_done(&rev.diffopt) < 0)
305 die(_("diff_setup_done failed"));
306 add_pending_object(&rev, head, NULL);
307 run_diff_index(&rev, 0);
308 }
309
310 static void describe_detached_head(const char *msg, struct commit *commit)
311 {
312 struct strbuf sb = STRBUF_INIT;
313 parse_commit(commit);
314 pp_commit_easy(CMIT_FMT_ONELINE, commit, &sb);
315 fprintf(stderr, "%s %s... %s\n", msg,
316 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV), sb.buf);
317 strbuf_release(&sb);
318 }
319
320 static int reset_tree(struct tree *tree, struct checkout_opts *o, int worktree)
321 {
322 struct unpack_trees_options opts;
323 struct tree_desc tree_desc;
324
325 memset(&opts, 0, sizeof(opts));
326 opts.head_idx = -1;
327 opts.update = worktree;
328 opts.skip_unmerged = !worktree;
329 opts.reset = 1;
330 opts.merge = 1;
331 opts.fn = oneway_merge;
332 opts.verbose_update = !o->quiet;
333 opts.src_index = &the_index;
334 opts.dst_index = &the_index;
335 parse_tree(tree);
336 init_tree_desc(&tree_desc, tree->buffer, tree->size);
337 switch (unpack_trees(1, &tree_desc, &opts)) {
338 case -2:
339 o->writeout_error = 1;
340 /*
341 * We return 0 nevertheless, as the index is all right
342 * and more importantly we have made best efforts to
343 * update paths in the work tree, and we cannot revert
344 * them.
345 */
346 case 0:
347 return 0;
348 default:
349 return 128;
350 }
351 }
352
353 struct branch_info {
354 const char *name; /* The short name used */
355 const char *path; /* The full name of a real branch */
356 struct commit *commit; /* The named commit */
357 };
358
359 static void setup_branch_path(struct branch_info *branch)
360 {
361 struct strbuf buf = STRBUF_INIT;
362
363 strbuf_branchname(&buf, branch->name);
364 if (strcmp(buf.buf, branch->name))
365 branch->name = xstrdup(buf.buf);
366 strbuf_splice(&buf, 0, 0, "refs/heads/", 11);
367 branch->path = strbuf_detach(&buf, NULL);
368 }
369
370 static int merge_working_tree(struct checkout_opts *opts,
371 struct branch_info *old, struct branch_info *new)
372 {
373 int ret;
374 struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file));
375 int newfd = hold_locked_index(lock_file, 1);
376
377 if (read_cache_preload(NULL) < 0)
378 return error(_("corrupt index file"));
379
380 resolve_undo_clear();
381 if (opts->force) {
382 ret = reset_tree(new->commit->tree, opts, 1);
383 if (ret)
384 return ret;
385 } else {
386 struct tree_desc trees[2];
387 struct tree *tree;
388 struct unpack_trees_options topts;
389
390 memset(&topts, 0, sizeof(topts));
391 topts.head_idx = -1;
392 topts.src_index = &the_index;
393 topts.dst_index = &the_index;
394
395 setup_unpack_trees_porcelain(&topts, "checkout");
396
397 refresh_cache(REFRESH_QUIET);
398
399 if (unmerged_cache()) {
400 error(_("you need to resolve your current index first"));
401 return 1;
402 }
403
404 /* 2-way merge to the new branch */
405 topts.initial_checkout = is_cache_unborn();
406 topts.update = 1;
407 topts.merge = 1;
408 topts.gently = opts->merge && old->commit;
409 topts.verbose_update = !opts->quiet;
410 topts.fn = twoway_merge;
411 topts.dir = xcalloc(1, sizeof(*topts.dir));
412 topts.dir->flags |= DIR_SHOW_IGNORED;
413 topts.dir->exclude_per_dir = ".gitignore";
414 tree = parse_tree_indirect(old->commit ?
415 old->commit->object.sha1 :
416 EMPTY_TREE_SHA1_BIN);
417 init_tree_desc(&trees[0], tree->buffer, tree->size);
418 tree = parse_tree_indirect(new->commit->object.sha1);
419 init_tree_desc(&trees[1], tree->buffer, tree->size);
420
421 ret = unpack_trees(2, trees, &topts);
422 if (ret == -1) {
423 /*
424 * Unpack couldn't do a trivial merge; either
425 * give up or do a real merge, depending on
426 * whether the merge flag was used.
427 */
428 struct tree *result;
429 struct tree *work;
430 struct merge_options o;
431 if (!opts->merge)
432 return 1;
433
434 /*
435 * Without old->commit, the below is the same as
436 * the two-tree unpack we already tried and failed.
437 */
438 if (!old->commit)
439 return 1;
440
441 /* Do more real merge */
442
443 /*
444 * We update the index fully, then write the
445 * tree from the index, then merge the new
446 * branch with the current tree, with the old
447 * branch as the base. Then we reset the index
448 * (but not the working tree) to the new
449 * branch, leaving the working tree as the
450 * merged version, but skipping unmerged
451 * entries in the index.
452 */
453
454 add_files_to_cache(NULL, NULL, 0);
455 /*
456 * NEEDSWORK: carrying over local changes
457 * when branches have different end-of-line
458 * normalization (or clean+smudge rules) is
459 * a pain; plumb in an option to set
460 * o.renormalize?
461 */
462 init_merge_options(&o);
463 o.verbosity = 0;
464 work = write_tree_from_memory(&o);
465
466 ret = reset_tree(new->commit->tree, opts, 1);
467 if (ret)
468 return ret;
469 o.ancestor = old->name;
470 o.branch1 = new->name;
471 o.branch2 = "local";
472 merge_trees(&o, new->commit->tree, work,
473 old->commit->tree, &result);
474 ret = reset_tree(new->commit->tree, opts, 0);
475 if (ret)
476 return ret;
477 }
478 }
479
480 if (write_cache(newfd, active_cache, active_nr) ||
481 commit_locked_index(lock_file))
482 die(_("unable to write new index file"));
483
484 if (!opts->force && !opts->quiet)
485 show_local_changes(&new->commit->object, &opts->diff_options);
486
487 return 0;
488 }
489
490 static void report_tracking(struct branch_info *new)
491 {
492 struct strbuf sb = STRBUF_INIT;
493 struct branch *branch = branch_get(new->name);
494
495 if (!format_tracking_info(branch, &sb))
496 return;
497 fputs(sb.buf, stdout);
498 strbuf_release(&sb);
499 }
500
501 static void detach_advice(const char *old_path, const char *new_name)
502 {
503 const char fmt[] =
504 "Note: checking out '%s'.\n\n"
505 "You are in 'detached HEAD' state. You can look around, make experimental\n"
506 "changes and commit them, and you can discard any commits you make in this\n"
507 "state without impacting any branches by performing another checkout.\n\n"
508 "If you want to create a new branch to retain commits you create, you may\n"
509 "do so (now or later) by using -b with the checkout command again. Example:\n\n"
510 " git checkout -b new_branch_name\n\n";
511
512 fprintf(stderr, fmt, new_name);
513 }
514
515 static void update_refs_for_switch(struct checkout_opts *opts,
516 struct branch_info *old,
517 struct branch_info *new)
518 {
519 struct strbuf msg = STRBUF_INIT;
520 const char *old_desc;
521 if (opts->new_branch) {
522 if (opts->new_orphan_branch) {
523 if (opts->new_branch_log && !log_all_ref_updates) {
524 int temp;
525 char log_file[PATH_MAX];
526 char *ref_name = mkpath("refs/heads/%s", opts->new_orphan_branch);
527
528 temp = log_all_ref_updates;
529 log_all_ref_updates = 1;
530 if (log_ref_setup(ref_name, log_file, sizeof(log_file))) {
531 fprintf(stderr, _("Can not do reflog for '%s'\n"),
532 opts->new_orphan_branch);
533 log_all_ref_updates = temp;
534 return;
535 }
536 log_all_ref_updates = temp;
537 }
538 }
539 else
540 create_branch(old->name, opts->new_branch, new->name,
541 opts->new_branch_force ? 1 : 0,
542 opts->new_branch_log, opts->track);
543 new->name = opts->new_branch;
544 setup_branch_path(new);
545 }
546
547 old_desc = old->name;
548 if (!old_desc && old->commit)
549 old_desc = sha1_to_hex(old->commit->object.sha1);
550 strbuf_addf(&msg, "checkout: moving from %s to %s",
551 old_desc ? old_desc : "(invalid)", new->name);
552
553 if (!strcmp(new->name, "HEAD") && !new->path && !opts->force_detach) {
554 /* Nothing to do. */
555 } else if (opts->force_detach || !new->path) { /* No longer on any branch. */
556 update_ref(msg.buf, "HEAD", new->commit->object.sha1, NULL,
557 REF_NODEREF, DIE_ON_ERR);
558 if (!opts->quiet) {
559 if (old->path && advice_detached_head)
560 detach_advice(old->path, new->name);
561 describe_detached_head(_("HEAD is now at"), new->commit);
562 }
563 } else if (new->path) { /* Switch branches. */
564 create_symref("HEAD", new->path, msg.buf);
565 if (!opts->quiet) {
566 if (old->path && !strcmp(new->path, old->path)) {
567 fprintf(stderr, _("Already on '%s'\n"),
568 new->name);
569 } else if (opts->new_branch) {
570 if (opts->branch_exists)
571 fprintf(stderr, _("Switched to and reset branch '%s'\n"), new->name);
572 else
573 fprintf(stderr, _("Switched to a new branch '%s'\n"), new->name);
574 } else {
575 fprintf(stderr, _("Switched to branch '%s'\n"),
576 new->name);
577 }
578 }
579 if (old->path && old->name) {
580 char log_file[PATH_MAX], ref_file[PATH_MAX];
581
582 git_snpath(log_file, sizeof(log_file), "logs/%s", old->path);
583 git_snpath(ref_file, sizeof(ref_file), "%s", old->path);
584 if (!file_exists(ref_file) && file_exists(log_file))
585 remove_path(log_file);
586 }
587 }
588 remove_branch_state();
589 strbuf_release(&msg);
590 if (!opts->quiet &&
591 (new->path || (!opts->force_detach && !strcmp(new->name, "HEAD"))))
592 report_tracking(new);
593 }
594
595 struct rev_list_args {
596 int argc;
597 int alloc;
598 const char **argv;
599 };
600
601 static void add_one_rev_list_arg(struct rev_list_args *args, const char *s)
602 {
603 ALLOC_GROW(args->argv, args->argc + 1, args->alloc);
604 args->argv[args->argc++] = s;
605 }
606
607 static int add_one_ref_to_rev_list_arg(const char *refname,
608 const unsigned char *sha1,
609 int flags,
610 void *cb_data)
611 {
612 add_one_rev_list_arg(cb_data, refname);
613 return 0;
614 }
615
616 static int clear_commit_marks_from_one_ref(const char *refname,
617 const unsigned char *sha1,
618 int flags,
619 void *cb_data)
620 {
621 struct commit *commit = lookup_commit_reference_gently(sha1, 1);
622 if (commit)
623 clear_commit_marks(commit, -1);
624 return 0;
625 }
626
627 static void describe_one_orphan(struct strbuf *sb, struct commit *commit)
628 {
629 parse_commit(commit);
630 strbuf_addstr(sb, " ");
631 strbuf_addstr(sb,
632 find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV));
633 strbuf_addch(sb, ' ');
634 pp_commit_easy(CMIT_FMT_ONELINE, commit, sb);
635 strbuf_addch(sb, '\n');
636 }
637
638 #define ORPHAN_CUTOFF 4
639 static void suggest_reattach(struct commit *commit, struct rev_info *revs)
640 {
641 struct commit *c, *last = NULL;
642 struct strbuf sb = STRBUF_INIT;
643 int lost = 0;
644 while ((c = get_revision(revs)) != NULL) {
645 if (lost < ORPHAN_CUTOFF)
646 describe_one_orphan(&sb, c);
647 last = c;
648 lost++;
649 }
650 if (ORPHAN_CUTOFF < lost) {
651 int more = lost - ORPHAN_CUTOFF;
652 if (more == 1)
653 describe_one_orphan(&sb, last);
654 else
655 strbuf_addf(&sb, _(" ... and %d more.\n"), more);
656 }
657
658 fprintf(stderr,
659 Q_(
660 /* The singular version */
661 "Warning: you are leaving %d commit behind, "
662 "not connected to\n"
663 "any of your branches:\n\n"
664 "%s\n",
665 /* The plural version */
666 "Warning: you are leaving %d commits behind, "
667 "not connected to\n"
668 "any of your branches:\n\n"
669 "%s\n",
670 /* Give ngettext() the count */
671 lost),
672 lost,
673 sb.buf);
674 strbuf_release(&sb);
675
676 if (advice_detached_head)
677 fprintf(stderr,
678 _(
679 "If you want to keep them by creating a new branch, "
680 "this may be a good time\nto do so with:\n\n"
681 " git branch new_branch_name %s\n\n"),
682 sha1_to_hex(commit->object.sha1));
683 }
684
685 /*
686 * We are about to leave commit that was at the tip of a detached
687 * HEAD. If it is not reachable from any ref, this is the last chance
688 * for the user to do so without resorting to reflog.
689 */
690 static void orphaned_commit_warning(struct commit *commit)
691 {
692 struct rev_list_args args = { 0, 0, NULL };
693 struct rev_info revs;
694
695 add_one_rev_list_arg(&args, "(internal)");
696 add_one_rev_list_arg(&args, sha1_to_hex(commit->object.sha1));
697 add_one_rev_list_arg(&args, "--not");
698 for_each_ref(add_one_ref_to_rev_list_arg, &args);
699 add_one_rev_list_arg(&args, "--");
700 add_one_rev_list_arg(&args, NULL);
701
702 init_revisions(&revs, NULL);
703 if (setup_revisions(args.argc - 1, args.argv, &revs, NULL) != 1)
704 die(_("internal error: only -- alone should have been left"));
705 if (prepare_revision_walk(&revs))
706 die(_("internal error in revision walk"));
707 if (!(commit->object.flags & UNINTERESTING))
708 suggest_reattach(commit, &revs);
709 else
710 describe_detached_head(_("Previous HEAD position was"), commit);
711
712 clear_commit_marks(commit, -1);
713 for_each_ref(clear_commit_marks_from_one_ref, NULL);
714 }
715
716 static int switch_branches(struct checkout_opts *opts, struct branch_info *new)
717 {
718 int ret = 0;
719 struct branch_info old;
720 unsigned char rev[20];
721 int flag;
722 memset(&old, 0, sizeof(old));
723 old.path = xstrdup(resolve_ref("HEAD", rev, 0, &flag));
724 old.commit = lookup_commit_reference_gently(rev, 1);
725 if (!(flag & REF_ISSYMREF)) {
726 free((char *)old.path);
727 old.path = NULL;
728 }
729
730 if (old.path && !prefixcmp(old.path, "refs/heads/"))
731 old.name = old.path + strlen("refs/heads/");
732
733 if (!new->name) {
734 new->name = "HEAD";
735 new->commit = old.commit;
736 if (!new->commit)
737 die(_("You are on a branch yet to be born"));
738 parse_commit(new->commit);
739 }
740
741 ret = merge_working_tree(opts, &old, new);
742 if (ret)
743 return ret;
744
745 if (!opts->quiet && !old.path && old.commit && new->commit != old.commit)
746 orphaned_commit_warning(old.commit);
747
748 update_refs_for_switch(opts, &old, new);
749
750 ret = post_checkout_hook(old.commit, new->commit, 1);
751 free((char *)old.path);
752 return ret || opts->writeout_error;
753 }
754
755 static int git_checkout_config(const char *var, const char *value, void *cb)
756 {
757 if (!strcmp(var, "diff.ignoresubmodules")) {
758 struct checkout_opts *opts = cb;
759 handle_ignore_submodules_arg(&opts->diff_options, value);
760 return 0;
761 }
762
763 if (!prefixcmp(var, "submodule."))
764 return parse_submodule_config_option(var, value);
765
766 return git_xmerge_config(var, value, NULL);
767 }
768
769 static int interactive_checkout(const char *revision, const char **pathspec,
770 struct checkout_opts *opts)
771 {
772 return run_add_interactive(revision, "--patch=checkout", pathspec);
773 }
774
775 struct tracking_name_data {
776 const char *name;
777 char *remote;
778 int unique;
779 };
780
781 static int check_tracking_name(const char *refname, const unsigned char *sha1,
782 int flags, void *cb_data)
783 {
784 struct tracking_name_data *cb = cb_data;
785 const char *slash;
786
787 if (prefixcmp(refname, "refs/remotes/"))
788 return 0;
789 slash = strchr(refname + 13, '/');
790 if (!slash || strcmp(slash + 1, cb->name))
791 return 0;
792 if (cb->remote) {
793 cb->unique = 0;
794 return 0;
795 }
796 cb->remote = xstrdup(refname);
797 return 0;
798 }
799
800 static const char *unique_tracking_name(const char *name)
801 {
802 struct tracking_name_data cb_data = { NULL, NULL, 1 };
803 cb_data.name = name;
804 for_each_ref(check_tracking_name, &cb_data);
805 if (cb_data.unique)
806 return cb_data.remote;
807 free(cb_data.remote);
808 return NULL;
809 }
810
811 static int parse_branchname_arg(int argc, const char **argv,
812 int dwim_new_local_branch_ok,
813 struct branch_info *new,
814 struct tree **source_tree,
815 unsigned char rev[20],
816 const char **new_branch)
817 {
818 int argcount = 0;
819 unsigned char branch_rev[20];
820 const char *arg;
821 int has_dash_dash;
822
823 /*
824 * case 1: git checkout <ref> -- [<paths>]
825 *
826 * <ref> must be a valid tree, everything after the '--' must be
827 * a path.
828 *
829 * case 2: git checkout -- [<paths>]
830 *
831 * everything after the '--' must be paths.
832 *
833 * case 3: git checkout <something> [<paths>]
834 *
835 * With no paths, if <something> is a commit, that is to
836 * switch to the branch or detach HEAD at it. As a special case,
837 * if <something> is A...B (missing A or B means HEAD but you can
838 * omit at most one side), and if there is a unique merge base
839 * between A and B, A...B names that merge base.
840 *
841 * With no paths, if <something> is _not_ a commit, no -t nor -b
842 * was given, and there is a tracking branch whose name is
843 * <something> in one and only one remote, then this is a short-hand
844 * to fork local <something> from that remote-tracking branch.
845 *
846 * Otherwise <something> shall not be ambiguous.
847 * - If it's *only* a reference, treat it like case (1).
848 * - If it's only a path, treat it like case (2).
849 * - else: fail.
850 *
851 */
852 if (!argc)
853 return 0;
854
855 if (!strcmp(argv[0], "--")) /* case (2) */
856 return 1;
857
858 arg = argv[0];
859 has_dash_dash = (argc > 1) && !strcmp(argv[1], "--");
860
861 if (!strcmp(arg, "-"))
862 arg = "@{-1}";
863
864 if (get_sha1_mb(arg, rev)) {
865 if (has_dash_dash) /* case (1) */
866 die(_("invalid reference: %s"), arg);
867 if (dwim_new_local_branch_ok &&
868 !check_filename(NULL, arg) &&
869 argc == 1) {
870 const char *remote = unique_tracking_name(arg);
871 if (!remote || get_sha1(remote, rev))
872 return argcount;
873 *new_branch = arg;
874 arg = remote;
875 /* DWIMmed to create local branch */
876 } else {
877 return argcount;
878 }
879 }
880
881 /* we can't end up being in (2) anymore, eat the argument */
882 argcount++;
883 argv++;
884 argc--;
885
886 new->name = arg;
887 setup_branch_path(new);
888
889 if (check_ref_format(new->path) == CHECK_REF_FORMAT_OK &&
890 resolve_ref(new->path, branch_rev, 1, NULL))
891 hashcpy(rev, branch_rev);
892 else
893 new->path = NULL; /* not an existing branch */
894
895 new->commit = lookup_commit_reference_gently(rev, 1);
896 if (!new->commit) {
897 /* not a commit */
898 *source_tree = parse_tree_indirect(rev);
899 } else {
900 parse_commit(new->commit);
901 *source_tree = new->commit->tree;
902 }
903
904 if (!*source_tree) /* case (1): want a tree */
905 die(_("reference is not a tree: %s"), arg);
906 if (!has_dash_dash) {/* case (3 -> 1) */
907 /*
908 * Do not complain the most common case
909 * git checkout branch
910 * even if there happen to be a file called 'branch';
911 * it would be extremely annoying.
912 */
913 if (argc)
914 verify_non_filename(NULL, arg);
915 } else {
916 argcount++;
917 argv++;
918 argc--;
919 }
920
921 return argcount;
922 }
923
924 int cmd_checkout(int argc, const char **argv, const char *prefix)
925 {
926 struct checkout_opts opts;
927 unsigned char rev[20];
928 struct branch_info new;
929 struct tree *source_tree = NULL;
930 char *conflict_style = NULL;
931 int patch_mode = 0;
932 int dwim_new_local_branch = 1;
933 struct option options[] = {
934 OPT__QUIET(&opts.quiet, "suppress progress reporting"),
935 OPT_STRING('b', NULL, &opts.new_branch, "branch",
936 "create and checkout a new branch"),
937 OPT_STRING('B', NULL, &opts.new_branch_force, "branch",
938 "create/reset and checkout a branch"),
939 OPT_BOOLEAN('l', NULL, &opts.new_branch_log, "create reflog for new branch"),
940 OPT_BOOLEAN(0, "detach", &opts.force_detach, "detach the HEAD at named commit"),
941 OPT_SET_INT('t', "track", &opts.track, "set upstream info for new branch",
942 BRANCH_TRACK_EXPLICIT),
943 OPT_STRING(0, "orphan", &opts.new_orphan_branch, "new branch", "new unparented branch"),
944 OPT_SET_INT('2', "ours", &opts.writeout_stage, "checkout our version for unmerged files",
945 2),
946 OPT_SET_INT('3', "theirs", &opts.writeout_stage, "checkout their version for unmerged files",
947 3),
948 OPT__FORCE(&opts.force, "force checkout (throw away local modifications)"),
949 OPT_BOOLEAN('m', "merge", &opts.merge, "perform a 3-way merge with the new branch"),
950 OPT_STRING(0, "conflict", &conflict_style, "style",
951 "conflict style (merge or diff3)"),
952 OPT_BOOLEAN('p', "patch", &patch_mode, "select hunks interactively"),
953 { OPTION_BOOLEAN, 0, "guess", &dwim_new_local_branch, NULL,
954 "second guess 'git checkout no-such-branch'",
955 PARSE_OPT_NOARG | PARSE_OPT_HIDDEN },
956 OPT_END(),
957 };
958
959 memset(&opts, 0, sizeof(opts));
960 memset(&new, 0, sizeof(new));
961
962 gitmodules_config();
963 git_config(git_checkout_config, &opts);
964
965 opts.track = BRANCH_TRACK_UNSPECIFIED;
966
967 argc = parse_options(argc, argv, prefix, options, checkout_usage,
968 PARSE_OPT_KEEP_DASHDASH);
969
970 /* we can assume from now on new_branch = !new_branch_force */
971 if (opts.new_branch && opts.new_branch_force)
972 die(_("-B cannot be used with -b"));
973
974 /* copy -B over to -b, so that we can just check the latter */
975 if (opts.new_branch_force)
976 opts.new_branch = opts.new_branch_force;
977
978 if (patch_mode && (opts.track > 0 || opts.new_branch
979 || opts.new_branch_log || opts.merge || opts.force
980 || opts.force_detach))
981 die (_("--patch is incompatible with all other options"));
982
983 if (opts.force_detach && (opts.new_branch || opts.new_orphan_branch))
984 die(_("--detach cannot be used with -b/-B/--orphan"));
985 if (opts.force_detach && 0 < opts.track)
986 die(_("--detach cannot be used with -t"));
987
988 /* --track without -b should DWIM */
989 if (0 < opts.track && !opts.new_branch) {
990 const char *argv0 = argv[0];
991 if (!argc || !strcmp(argv0, "--"))
992 die (_("--track needs a branch name"));
993 if (!prefixcmp(argv0, "refs/"))
994 argv0 += 5;
995 if (!prefixcmp(argv0, "remotes/"))
996 argv0 += 8;
997 argv0 = strchr(argv0, '/');
998 if (!argv0 || !argv0[1])
999 die (_("Missing branch name; try -b"));
1000 opts.new_branch = argv0 + 1;
1001 }
1002
1003 if (opts.new_orphan_branch) {
1004 if (opts.new_branch)
1005 die(_("--orphan and -b|-B are mutually exclusive"));
1006 if (opts.track > 0)
1007 die(_("--orphan cannot be used with -t"));
1008 opts.new_branch = opts.new_orphan_branch;
1009 }
1010
1011 if (conflict_style) {
1012 opts.merge = 1; /* implied */
1013 git_xmerge_config("merge.conflictstyle", conflict_style, NULL);
1014 }
1015
1016 if (opts.force && opts.merge)
1017 die(_("git checkout: -f and -m are incompatible"));
1018
1019 /*
1020 * Extract branch name from command line arguments, so
1021 * all that is left is pathspecs.
1022 *
1023 * Handle
1024 *
1025 * 1) git checkout <tree> -- [<paths>]
1026 * 2) git checkout -- [<paths>]
1027 * 3) git checkout <something> [<paths>]
1028 *
1029 * including "last branch" syntax and DWIM-ery for names of
1030 * remote branches, erroring out for invalid or ambiguous cases.
1031 */
1032 if (argc) {
1033 int dwim_ok =
1034 !patch_mode &&
1035 dwim_new_local_branch &&
1036 opts.track == BRANCH_TRACK_UNSPECIFIED &&
1037 !opts.new_branch;
1038 int n = parse_branchname_arg(argc, argv, dwim_ok,
1039 &new, &source_tree, rev, &opts.new_branch);
1040 argv += n;
1041 argc -= n;
1042 }
1043
1044 if (opts.track == BRANCH_TRACK_UNSPECIFIED)
1045 opts.track = git_branch_track;
1046
1047 if (argc) {
1048 const char **pathspec = get_pathspec(prefix, argv);
1049
1050 if (!pathspec)
1051 die(_("invalid path specification"));
1052
1053 if (patch_mode)
1054 return interactive_checkout(new.name, pathspec, &opts);
1055
1056 /* Checkout paths */
1057 if (opts.new_branch) {
1058 if (argc == 1) {
1059 die(_("git checkout: updating paths is incompatible with switching branches.\nDid you intend to checkout '%s' which can not be resolved as commit?"), argv[0]);
1060 } else {
1061 die(_("git checkout: updating paths is incompatible with switching branches."));
1062 }
1063 }
1064
1065 if (opts.force_detach)
1066 die(_("git checkout: --detach does not take a path argument"));
1067
1068 if (1 < !!opts.writeout_stage + !!opts.force + !!opts.merge)
1069 die(_("git checkout: --ours/--theirs, --force and --merge are incompatible when\nchecking out of the index."));
1070
1071 return checkout_paths(source_tree, pathspec, prefix, &opts);
1072 }
1073
1074 if (patch_mode)
1075 return interactive_checkout(new.name, NULL, &opts);
1076
1077 if (opts.new_branch) {
1078 struct strbuf buf = STRBUF_INIT;
1079
1080 opts.branch_exists = validate_new_branchname(opts.new_branch, &buf,
1081 !!opts.new_branch_force, 0);
1082
1083 strbuf_release(&buf);
1084 }
1085
1086 if (new.name && !new.commit) {
1087 die(_("Cannot switch branch to a non-commit."));
1088 }
1089 if (opts.writeout_stage)
1090 die(_("--ours/--theirs is incompatible with switching branches."));
1091
1092 return switch_branches(&opts, &new);
1093 } | __label__pos | 0.984757 |
KiCad PCB EDA Suite
Loading...
Searching...
No Matches
ellipse.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2022 KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation, either version 3 of the License, or (at your
9 * option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License along
17 * with this program. If not, see <http://www.gnu.org/licenses/>.
18 */
19
20#include <geometry/ellipse.h>
21
22
23template <typename NumericType>
24ELLIPSE<NumericType>::ELLIPSE( const VECTOR2<NumericType>& aCenter, NumericType aMajorRadius,
25 NumericType aMinorRadius, EDA_ANGLE aRotation, EDA_ANGLE aStartAngle,
26 EDA_ANGLE aEndAngle ) :
27 Center( aCenter ),
28 MajorRadius( aMajorRadius ),
29 MinorRadius( aMinorRadius ),
30 Rotation( aRotation ),
31 StartAngle( aStartAngle ),
32 EndAngle( aEndAngle )
33{
34}
35
36
37template <typename NumericType>
39 const VECTOR2<NumericType>& aMajor, double aRatio,
40 EDA_ANGLE aStartAngle, EDA_ANGLE aEndAngle ) :
41 Center( aCenter ),
42 StartAngle( aStartAngle ),
43 EndAngle( aEndAngle )
44{
45 MajorRadius = aMajor.EuclideanNorm();
46 MinorRadius = NumericType( MajorRadius * aRatio );
47 Rotation = EDA_ANGLE( std::atan2( aMajor.y, aMajor.x ), RADIANS_T );
48}
50template class ELLIPSE<double>;
51template class ELLIPSE<int>;
This class was created to handle importing ellipses from other file formats that support them nativel...
Definition: ellipse.h:34
NumericType MinorRadius
Definition: ellipse.h:69
EDA_ANGLE Rotation
Definition: ellipse.h:70
NumericType MajorRadius
Definition: ellipse.h:68
ELLIPSE()=default
Define a general 2D-vector/point.
Definition: vector2d.h:70
T EuclideanNorm() const
Compute the Euclidean norm of the vector, which is defined as sqrt(x ** 2 + y ** 2).
Definition: vector2d.h:278
@ RADIANS_T
Definition: eda_angle.h:32 | __label__pos | 0.930302 |
XPathDocument.cs source code in C# .NET
Source code for the .NET framework in C#
Code:
/ 4.0 / 4.0 / untmp / DEVDIV_TFS / Dev10 / Releases / RTMRel / ndp / fx / src / Xml / System / Xml / XPath / XPathDocument.cs / 1305376 / XPathDocument.cs
//------------------------------------------------------------------------------
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// [....]
//-----------------------------------------------------------------------------
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
using System.Collections.Generic;
using MS.Internal.Xml.Cache;
using System.Diagnostics;
using System.Text;
using System.Runtime.Versioning;
namespace System.Xml.XPath {
///
/// XDocument follows the XPath/XQuery data model. All nodes in the tree reference the document,
/// and the document references the root node of the tree. All namespaces are stored out-of-line,
/// in an Element --> In-Scope-Namespaces map.
///
public class XPathDocument : IXPathNavigable {
private XPathNode[] pageText, pageRoot, pageXmlNmsp;
private int idxText, idxRoot, idxXmlNmsp;
private XmlNameTable nameTable;
private bool hasLineInfo;
private Dictionary mapNmsp;
private Dictionary idValueMap;
///
/// Flags that control Load behavior.
///
internal enum LoadFlags {
None = 0,
AtomizeNames = 1, // Do not assume that names passed to XPathDocumentBuilder have been pre-atomized, and atomize them
Fragment = 2, // Create a document with no document node
}
//-----------------------------------------------
// Creation Methods
//-----------------------------------------------
///
/// Create a new empty document.
///
internal XPathDocument() {
this.nameTable = new NameTable();
}
///
/// Create a new empty document. All names should be atomized using "nameTable".
///
internal XPathDocument(XmlNameTable nameTable) {
if (nameTable == null)
throw new ArgumentNullException("nameTable");
this.nameTable = nameTable;
}
///
/// Create a new document and load the content from the reader.
///
public XPathDocument(XmlReader reader) : this(reader, XmlSpace.Default) {
}
///
/// Create a new document from "reader", with whitespace handling controlled according to "space".
///
public XPathDocument(XmlReader reader, XmlSpace space) {
if (reader == null)
throw new ArgumentNullException("reader");
LoadFromReader(reader, space);
}
///
/// Create a new document and load the content from the text reader.
///
public XPathDocument(TextReader textReader) {
XmlTextReaderImpl reader = SetupReader(new XmlTextReaderImpl(string.Empty, textReader));
try {
LoadFromReader(reader, XmlSpace.Default);
}
finally {
reader.Close();
}
}
///
/// Create a new document and load the content from the stream.
///
public XPathDocument(Stream stream) {
XmlTextReaderImpl reader = SetupReader(new XmlTextReaderImpl(string.Empty, stream));
try {
LoadFromReader(reader, XmlSpace.Default);
}
finally {
reader.Close();
}
}
///
/// Create a new document and load the content from the Uri.
///
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
public XPathDocument(string uri) : this(uri, XmlSpace.Default) {
}
///
/// Create a new document and load the content from the Uri, with whitespace handling controlled according to "space".
///
[ResourceConsumption(ResourceScope.Machine)]
[ResourceExposure(ResourceScope.Machine)]
public XPathDocument(string uri, XmlSpace space) {
XmlTextReaderImpl reader = SetupReader(new XmlTextReaderImpl(uri));
try {
LoadFromReader(reader, space);
}
finally {
reader.Close();
}
}
///
/// Create a writer that can be used to create nodes in this document. The root node will be assigned "baseUri", and flags
/// can be passed to indicate that names should be atomized by the builder and/or a fragment should be created.
///
internal XmlRawWriter LoadFromWriter(LoadFlags flags, string baseUri) {
return new XPathDocumentBuilder(this, null, baseUri, flags);
}
///
/// Create a writer that can be used to create nodes in this document. The root node will be assigned "baseUri", and flags
/// can be passed to indicate that names should be atomized by the builder and/or a fragment should be created.
///
internal void LoadFromReader(XmlReader reader, XmlSpace space) {
XPathDocumentBuilder builder;
IXmlLineInfo lineInfo;
string xmlnsUri;
bool topLevelReader;
int initialDepth;
if (reader == null)
throw new ArgumentNullException("reader");
// Determine line number provider
lineInfo = reader as IXmlLineInfo;
if (lineInfo == null || !lineInfo.HasLineInfo())
lineInfo = null;
this.hasLineInfo = (lineInfo != null);
this.nameTable = reader.NameTable;
builder = new XPathDocumentBuilder(this, lineInfo, reader.BaseURI, LoadFlags.None);
try {
// Determine whether reader is in initial state
topLevelReader = (reader.ReadState == ReadState.Initial);
initialDepth = reader.Depth;
// Get atomized xmlns uri
Debug.Assert((object) this.nameTable.Get(string.Empty) == (object) string.Empty, "NameTable must contain atomized string.Empty");
xmlnsUri = this.nameTable.Get(XmlReservedNs.NsXmlNs);
// Read past Initial state; if there are no more events then load is complete
if (topLevelReader && !reader.Read())
return;
// Read all events
do {
// If reader began in intermediate state, return when all siblings have been read
if (!topLevelReader && reader.Depth < initialDepth)
return;
switch (reader.NodeType) {
case XmlNodeType.Element: {
bool isEmptyElement = reader.IsEmptyElement;
builder.WriteStartElement(reader.Prefix, reader.LocalName, reader.NamespaceURI, reader.BaseURI);
// Add attribute and namespace nodes to element
while (reader.MoveToNextAttribute()) {
string namespaceUri = reader.NamespaceURI;
if ((object) namespaceUri == (object) xmlnsUri) {
if (reader.Prefix.Length == 0) {
// Default namespace declaration "xmlns"
Debug.Assert(reader.LocalName == "xmlns");
builder.WriteNamespaceDeclaration(string.Empty, reader.Value);
}
else {
Debug.Assert(reader.Prefix == "xmlns");
builder.WriteNamespaceDeclaration(reader.LocalName, reader.Value);
}
}
else {
builder.WriteStartAttribute(reader.Prefix, reader.LocalName, namespaceUri);
builder.WriteString(reader.Value, TextBlockType.Text);
builder.WriteEndAttribute();
}
}
if (isEmptyElement)
builder.WriteEndElement(true);
break;
}
case XmlNodeType.EndElement:
builder.WriteEndElement(false);
break;
case XmlNodeType.Text:
case XmlNodeType.CDATA:
builder.WriteString(reader.Value, TextBlockType.Text);
break;
case XmlNodeType.SignificantWhitespace:
if (reader.XmlSpace == XmlSpace.Preserve)
builder.WriteString(reader.Value, TextBlockType.SignificantWhitespace);
else
// Significant whitespace without xml:space="preserve" is not significant in XPath/XQuery data model
goto case XmlNodeType.Whitespace;
break;
case XmlNodeType.Whitespace:
// We intentionally ignore the reader.XmlSpace property here and blindly trust
// the reported node type. If the reported information is not in [....]
// (in this case if the reader.XmlSpace == Preserve) then we make the choice
// to trust the reported node type. Since we have no control over the input reader
// we can't even assert here.
// Always filter top-level whitespace
if (space == XmlSpace.Preserve && (!topLevelReader || reader.Depth != 0))
builder.WriteString(reader.Value, TextBlockType.Whitespace);
break;
case XmlNodeType.Comment:
builder.WriteComment(reader.Value);
break;
case XmlNodeType.ProcessingInstruction:
builder.WriteProcessingInstruction(reader.LocalName, reader.Value, reader.BaseURI);
break;
case XmlNodeType.EntityReference:
reader.ResolveEntity();
break;
case XmlNodeType.DocumentType:
// Create ID tables
IDtdInfo info = reader.DtdInfo;
if (info != null)
builder.CreateIdTables(info);
break;
case XmlNodeType.EndEntity:
case XmlNodeType.None:
case XmlNodeType.XmlDeclaration:
break;
}
}
while (reader.Read());
}
finally {
builder.Close();
}
}
///
/// Create a navigator positioned on the root node of the document.
///
public XPathNavigator CreateNavigator() {
return new XPathDocumentNavigator(this.pageRoot, this.idxRoot, null, 0);
}
//-----------------------------------------------
// Document Properties
//-----------------------------------------------
///
/// Return the name table used to atomize all name parts (local name, namespace uri, prefix).
///
internal XmlNameTable NameTable {
get { return this.nameTable; }
}
///
/// Return true if line number information is recorded in the cache.
///
internal bool HasLineInfo {
get { return this.hasLineInfo; }
}
///
/// Return the singleton collapsed text node associated with the document. One physical text node
/// represents each logical text node in the document that is the only content-typed child of its
/// element parent.
///
internal int GetCollapsedTextNode(out XPathNode[] pageText) {
pageText = this.pageText;
return this.idxText;
}
///
/// Set the page and index where the singleton collapsed text node is stored.
///
internal void SetCollapsedTextNode(XPathNode[] pageText, int idxText) {
this.pageText = pageText;
this.idxText = idxText;
}
///
/// Return the root node of the document. This may not be a node of type XPathNodeType.Root if this
/// is a document fragment.
///
internal int GetRootNode(out XPathNode[] pageRoot) {
pageRoot = this.pageRoot;
return this.idxRoot;
}
///
/// Set the page and index where the root node is stored.
///
internal void SetRootNode(XPathNode[] pageRoot, int idxRoot) {
this.pageRoot = pageRoot;
this.idxRoot = idxRoot;
}
///
/// Every document has an implicit xmlns:xml namespace node.
///
internal int GetXmlNamespaceNode(out XPathNode[] pageXmlNmsp) {
pageXmlNmsp = this.pageXmlNmsp;
return this.idxXmlNmsp;
}
///
/// Set the page and index where the implicit xmlns:xml node is stored.
///
internal void SetXmlNamespaceNode(XPathNode[] pageXmlNmsp, int idxXmlNmsp) {
this.pageXmlNmsp = pageXmlNmsp;
this.idxXmlNmsp = idxXmlNmsp;
}
///
/// Associate a namespace node with an element.
///
internal void AddNamespace(XPathNode[] pageElem, int idxElem, XPathNode[] pageNmsp, int idxNmsp) {
Debug.Assert(pageElem[idxElem].NodeType == XPathNodeType.Element && pageNmsp[idxNmsp].NodeType == XPathNodeType.Namespace);
if (this.mapNmsp == null)
this.mapNmsp = new Dictionary();
this.mapNmsp.Add(new XPathNodeRef(pageElem, idxElem), new XPathNodeRef(pageNmsp, idxNmsp));
}
///
/// Lookup the namespace nodes associated with an element.
///
internal int LookupNamespaces(XPathNode[] pageElem, int idxElem, out XPathNode[] pageNmsp) {
XPathNodeRef nodeRef = new XPathNodeRef(pageElem, idxElem);
Debug.Assert(pageElem[idxElem].NodeType == XPathNodeType.Element);
// Check whether this element has any local namespaces
if (this.mapNmsp == null || !this.mapNmsp.ContainsKey(nodeRef)) {
pageNmsp = null;
return 0;
}
// Yes, so return the page and index of the first local namespace node
nodeRef = this.mapNmsp[nodeRef];
pageNmsp = nodeRef.Page;
return nodeRef.Index;
}
///
/// Add an element indexed by ID value.
///
internal void AddIdElement(string id, XPathNode[] pageElem, int idxElem) {
if (this.idValueMap == null)
this.idValueMap = new Dictionary();
if (!this.idValueMap.ContainsKey(id))
this.idValueMap.Add(id, new XPathNodeRef(pageElem, idxElem));
}
///
/// Lookup the element node associated with the specified ID value.
///
internal int LookupIdElement(string id, out XPathNode[] pageElem) {
XPathNodeRef nodeRef;
if (this.idValueMap == null || !this.idValueMap.ContainsKey(id)) {
pageElem = null;
return 0;
}
// Extract page and index from XPathNodeRef
nodeRef = this.idValueMap[id];
pageElem = nodeRef.Page;
return nodeRef.Index;
}
//-----------------------------------------------
// Helper Methods
//-----------------------------------------------
///
/// Set properties on the reader so that it is backwards-compatible with V1.
///
private XmlTextReaderImpl SetupReader(XmlTextReaderImpl reader) {
reader.EntityHandling = EntityHandling.ExpandEntities;
reader.XmlValidatingReaderCompatibilityMode = true;
return reader;
}
}
}
// File provided for Reference Use Only by Microsoft Corporation (c) 2007.
Link Menu
Network programming in C#, Network Programming in VB.NET, Network Programming in .NET
This book is available now!
Buy at Amazon US or
Buy at Amazon UK | __label__pos | 0.995849 |
Loyola University Maryland
Technology Services
WebCRD: Submit Jobs to Printing Services
image divider
WebCRD allows the Loyola community to send job requests to Printing Services via their computer. If you have a print job such as flyers, banners, brochures, or any other professional print request, just print the file from within your program to your printer entitled “Printing Services”.
Why is using WebCRD better than sending the file over email or other transfer mechanism?
Prior to now, you would email the document or use some other method to get it to Printing Services. This caused issues with the incorrect file formats, missing fonts, etc. Now, using WebCRD, you can submit your file straight to Printing Services right from the program you are in. So if you are using Word, or Excel for example, you would go to File/Print, and then look for the Printing Services driver. Using the system, an individual has the ability to choose the various print options that they want, see a real time print proof of what it will look like, and also get up to the minute pricing on their print job. The use of the system will ensure that users get the file printed exactly how they want it, with the right fonts, colors, and layout.
How to use WebCRD
When you are ready to submit your job, using your chosen application’s menu system, go to File/Print, and then look for the printer entitled "Printing Services". You would hit print, and it would auto-generate your file into a PDF and upload it to the website. A new window will open and you will need to log into the system using your Loyola username and password. Once logged in, the website functions like a shopping cart where you pick all the print options for your file and also put in your GL number to handle the charges. There is a quick start guide on the home page with step by step instructions and screenshots.
Can I upload a file instead of using the file/print command?
If a person does not want to use the printer driver, they can go straight to the Printing Service Website and log in and then upload their file there. All files must be in PDF format, so they would need to be convert first. | __label__pos | 0.502866 |
How to Recover Data From Wasabi Cloud Storage with DPX vPlus
Introduction
DPX vPlus is a reliable backup and snapshot management solution that offers seamless data recovery for virtual environments and Microsoft 365. In a previous blog, we provided the steps for How To Use Wasabi Hot Cloud Storage for DPX vPlus Backup Storage. In this step-by-step guide, we will walk you through the process of recovering data from Wasabi Cloud Storage using DPX vPlus. Whether you need to recover virtual machines or Microsoft 365 resources, this guide has got you covered. Let’s get started!
Note: This guide assumes that you have already backed up your data to Wasabi cloud storage and have properly configured DPX vPlus.
Ad-Hoc Recovery of Virtual Machines
• Open DPX vPlus Dashboard
1. On the left-hand menu, click on “Virtual Environments” and then “Instances” to access the list of discovered virtual machines.
2. Scroll or use the search bar to find the specific VM you want to recover.
• Initiate the Restore Job:
1. Click the second button from the right to open the Restore job creation wizard.
• Select the Snapshot:
1. In the Restore Job wizard, choose the snapshot that you wish to recover.
2. Look for the snapshot ending with the destination that indicates it is stored in Wasabi object storage.
• Specify the Recovery Destination:
1. Select “Restore to Hypervisor” and choose the hypervisor host where you want to recover the VM.
• Configure the Restore Options:
1. Complete the restore wizard, following the specific process for your hypervisor.
2. Depending on your requirements, you may have options to delete the existing VM or change the name of the new VM.
• Start the Restore Task:
1. Click “Restore” to initiate the task.
2. Monitor the progress by accessing the “Workflow Executions Console” at the bottom of the screen.
Ad-Hoc Recovery of Microsoft 365 Resources
• Open DPX vPlus Dashboard:
1. On the left-hand menu, click on “Cloud” and then “Instances” to view the list of Microsoft 365 resources.
• Locate the Owner of the Resource:
1. Scroll or use the search bar to find the owner of the resource you need to recover.
• Access Protected Data:
1. Click on the name of the owner to open a new window.
2. Scroll down until you find the “Protected Data” tab and open it.
• Select the Application:
1. On the left side, you will see tabs for each MS application protected for that user (e.g., Exchange, OneDrive, Chats).
2. Browse through the tabs to find the specific application that contains the resource you want to recover.
• Choose the Restore Option:
1. Browse through the application (e.g., OneDrive, Mailbox) to find the individual resource you need to recover.
2. Select the item you want to restore.
• Restore the Item:
1. To restore the item back to a location within MS 365 cloud, click the “Restore” button in the top-right corner.
2. This will open a short Restore wizard where you can specify alternate restoration paths, overwrite existing files, or choose an alternate User, Group, Team, or Site for restoration.
3. Alternatively, to download the item to your local machine, click the “Download” button in the top-right corner.
4. Once the download preparation is complete, you can find the item for download under the “Download” section in the “Cloud” tab of the left-hand menu.
Scheduled Recovery Using Recovery Plans
• Open DPX vPlus Dashboard:
1. On the left-hand menu, click on “Virtual Environments” and then “Recovery Plans.”
2. Click the “Create” button on the right-hand side to create a new Recovery Plan.
• Create the Recovery Plan:
1. Give the new Recovery Plan a descriptive name and click “Save”.
2. Rules can be added to this plan later.
• Add a Rule:
1. Scroll down and click “Add Rule” to schedule a recurring restore.
• Configure the Rule:
1. Provide a name for the rule and click “Next”.
2. Select the Virtualization Platform and the VM(s) you want to include in this plan.
3. Click “Next”.
• Select or Create the Schedule:
1. Choose an existing schedule or create a new one that suits your recovery plan.
2. Click “Next”.
• Define Restore Parameters:
1. Proceed through the “Restore Parameters” section, specifying details such as the backup to use for recovery, recovery destination, storage, and the name for the new VM.
2. Once done, click “Save”.
Conclusion
With DPX vPlus and Wasabi Cloud Storage, recovering data from backups has never been easier. In this guide, we covered the step-by-step process for ad-hoc recovery of virtual machines and Microsoft 365 resources. Additionally, we explored scheduled recovery plans to automate recurring restores. By following these instructions, you can confidently recover your valuable data using DPX vPlus and Wasabi Cloud Storage. Contact us for a demonstration, trial and pricing.
Let us show you around | __label__pos | 0.980047 |
AdHocNetworks Glossary
From SarWiki
Jump to: navigation, search
Please add all technical terms that you encountered during the seminar, including a verbose description of their meaning. Please keep those terms in an alphabetical order.
Word, Description of the word
• Attenuation The attenuation denotes the loss of intensity a signal expieriences on its way to a reciever.
• Multi-path fading A phenomenon from the domain of wireless networks. A signal emitted by a source node follows different paths on its way to the reciever node. In particular, the reciever node not only recieves the signal following the "line of sight" path, but also copies of this signal with a slight offset in time. Those copies followed a longer path and probably got reflected several times before reaching their destination. Because of these reflections the copies tend to be increasingly attenuated as time progresses.
• Neighbor abstraction The neighbor abstraction is based on the assumption, that the nodes in a network can be partitioned into two sets of pairs, according to whether the two nodes in each pair can or can not communicate directly. Thus for any given node there exists a set S_n of its neighbors. This assumption holds for wired networks. | __label__pos | 0.606918 |
The Introduction to Quantum Computing
«Quantum Computing» is among those terms that are widely discussed but often poorly understood. The reasons of this state of affairs may be numerous, but possibly the most significant among them is that it is a relatively new scientific area, and it’s clear interpretations are not yet widely spread. The main obstacle here is the word «quantum», which refers to quantum mechanics — one of the most counter-intuitive ways to describe our world.
But fear not! This is not a course on quantum mechanics. We will gently touch it in the beginning and then leave it apart, concentrating on the mathematical model of quantum computer, generously developed for us by physicists. This doesn’t mean that the whole course is mathematics either (however there will be enough of it). We will build a simple working quantum computer with our bare hands, and we will consider some algorithms, designed for bigger quantum computers which are not yet developed.
The course material is designed for those computer scientists, engineers and programmers who believe, that there’s something else than just HLL programming, that will move our computing power further into infinity.
Since the course is introductory, the only prerequisites are complex numbers and linear algebra. These two are required and they have to be enough.
Happy learning!
Записаться на курс:
Авторы курса:
• Sergei Sysoev
Candidate of Physical and Mathematical Sciences, Department of System Programming | __label__pos | 0.673789 |
Welcome, guest | Sign In | My Account | Store | Cart
This recipe manually counts the number of sub-directories and files can be found in a directory. It was an experimental program from long ago used to learn more about Python. This is committed for archival to be run under Python 2.5 or later versions.
Python, 18 lines
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import os, sys
def main():
if len(sys.argv) - 1:
engine(' '.join(sys.argv[1:]))
else:
print os.path.basename(sys.argv[0]), '<directory>'
def engine(path):
directories = files = 0
for information in os.walk(path):
directories += len(information[1])
files += len(information[2])
print 'Directories =', directories
print 'Files =', files
if __name__ == '__main__':
main()
1 comment
James Radtke 9 years, 4 months ago # | flag
Thanks for publishing this script. I'm just getting started. Being able to see simple scripts that do things that are somewhat easy to grasp is very helpful for my learning.
| __label__pos | 0.807212 |
CPM Homework Banner
Home > A2C > Chapter 2 > Lesson 2.1.7 > Problem 2-102
2-102.
For the function , find the value of each expression below.
1.
Substitute for in the given equation and then evaluate.
1.
1.
1.
1. Find at least one value of for which .
Let in the original equation and then solve for .
, ,
1. If , find .
Remove parentheses. Pay attention to the minus sign in front of . Combine like terms. | __label__pos | 0.999946 |
Bayonne2 / Common C++ 2 Framework
All Data Structures Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
oqueue.h
Go to the documentation of this file.
1 // Copyright (C) 2001,2002,2004,2005 Federico Montesino Pouzols <[email protected]>.
2 //
3 // This program is free software; you can redistribute it and/or modify
4 // it under the terms of the GNU General Public License as published by
5 // the Free Software Foundation; either version 2 of the License, or
6 // (at your option) any later version.
7 //
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 // GNU General Public License for more details.
12 //
13 // You should have received a copy of the GNU General Public License
14 // along with this program; if not, write to the Free Software
15 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
16 //
17 // As a special exception, you may use this file as part of a free software
18 // library without restriction. Specifically, if other files instantiate
19 // templates or use macros or inline functions from this file, or you compile
20 // this file and link it with other files to produce an executable, this
21 // file does not by itself cause the resulting executable to be covered by
22 // the GNU General Public License. This exception does not however
23 // invalidate any other reasons why the executable file might be covered by
24 // the GNU General Public License.
25 //
26 // This exception applies only to the code released under the name GNU
27 // ccRTP. If you copy code from other releases into a copy of GNU
28 // ccRTP, as the General Public License permits, the exception does
29 // not apply to the code that you add in this way. To avoid misleading
30 // anyone as to the status of such modified files, you must delete
31 // this exception notice from them.
32 //
33 // If you write modifications of your own for GNU ccRTP, it is your choice
34 // whether to permit this exception to apply to your modifications.
35 // If you do not wish that, delete this exception notice.
36 //
37
44 #ifndef CCXX_RTP_OQUEUE_H_
45 #define CCXX_RTP_OQUEUE_H_
46
47 #include <ccrtp/queuebase.h>
48 #include <ccrtp/CryptoContext.h>
49 #include <list>
50
51 #ifdef CCXX_NAMESPACES
52 namespace ost {
53 #endif
54
69 {
70 protected:
72 std::list<TransportAddress*> destList;
73
74 public:
76
78
82 inline bool isSingleDestination() const
83 { return (1 == destList.size()); }
84
86 { return destList.front(); }
87
88 inline void lockDestinationList() const
89 { destinationLock.readLock(); }
90
91 inline void unlockDestinationList() const
92 { destinationLock.unlock(); }
93
94 protected:
95 inline void writeLockDestinationList() const
96 { destinationLock.writeLock(); }
97
101 bool
102 addDestinationToList(const InetAddress& ia, tpport_t data,
103 tpport_t control);
104
108 bool removeDestinationFromList(const InetAddress& ia,
109 tpport_t dataPort,
110 tpport_t controlPort);
111
113 {
115 networkAddress(na), dataTransportPort(dtp),
116 controlTransportPort(ctp)
117 { }
118
119 inline const InetAddress& getNetworkAddress() const
120 { return networkAddress; }
121
123 { return dataTransportPort; }
124
126 { return controlTransportPort; }
127
129 tpport_t dataTransportPort, controlTransportPort;
130 };
131
132 private:
134 };
135
136 #ifdef CCXX_IPV6
137
145 class __EXPORT DestinationListHandlerIPV6
146 {
147 protected:
148 struct TransportAddressIPV6;
149 std::list<TransportAddressIPV6*> destListIPV6;
150
151 public:
152 DestinationListHandlerIPV6();
153
154 ~DestinationListHandlerIPV6();
155
159 inline bool isSingleDestinationIPV6() const
160 { return (1 == destListIPV6.size()); }
161
162 inline TransportAddressIPV6* getFirstDestinationIPV6() const
163 { return destListIPV6.front(); }
164
165 inline void lockDestinationListIPV6() const
166 { destinationLock.readLock(); }
167
168 inline void unlockDestinationListIPV6() const
169 { destinationLock.unlock(); }
170
171 protected:
172 inline void writeLockDestinationListIPV6() const
173 { destinationLock.writeLock(); }
174
178 bool
179 addDestinationToListIPV6(const IPV6Address& ia, tpport_t data,
180 tpport_t control);
181
185 bool removeDestinationFromListIPV6(const IPV6Address& ia,
186 tpport_t dataPort,
187 tpport_t controlPort);
188
189 struct TransportAddressIPV6
190 {
191 TransportAddressIPV6(IPV6Address na, tpport_t dtp, tpport_t ctp) :
192 networkAddress(na), dataTransportPort(dtp),
193 controlTransportPort(ctp)
194 { }
195
196 inline const IPV6Address& getNetworkAddress() const
197 { return networkAddress; }
198
199 inline tpport_t getDataTransportPort() const
200 { return dataTransportPort; }
201
202 inline tpport_t getControlTransportPort() const
203 { return controlTransportPort; }
204
205 IPV6Address networkAddress;
206 tpport_t dataTransportPort, controlTransportPort;
207 };
208
209 private:
210 mutable ThreadLock destinationLock;
211 };
212
213 #endif
214
223 public OutgoingDataQueueBase,
224 #ifdef CCXX_IPV6
225 protected DestinationListHandlerIPV6,
226 #endif
227 protected DestinationListHandler
228 {
229 public:
230 #ifdef CCXX_IPV6
231 bool
232 addDestination(const IPV6Address& ia,
233 tpport_t dataPort = DefaultRTPDataPort,
234 tpport_t controlPort = 0);
235
236 bool
237 forgetDestination(const IPV6Address& ia,
238 tpport_t dataPort = DefaultRTPDataPort,
239 tpport_t controlPort = 0);
240
241 #endif
242
243 bool
244 addDestination(const InetHostAddress& ia,
245 tpport_t dataPort = DefaultRTPDataPort,
246 tpport_t controlPort = 0);
247
248 bool
249 addDestination(const InetMcastAddress& ia,
250 tpport_t dataPort = DefaultRTPDataPort,
251 tpport_t controlPort = 0);
252
253 bool
254 forgetDestination(const InetHostAddress& ia,
255 tpport_t dataPort = DefaultRTPDataPort,
256 tpport_t controlPort = 0);
257
258 bool
259 forgetDestination(const InetMcastAddress& ia,
260 tpport_t dataPort = DefaultRTPDataPort,
261 tpport_t controlPort = 0);
262
268 void
269 addContributor(uint32 csrc);
270
274 bool
275 removeContributor(uint32 csrc);
276
282 bool
283 isSending() const;
284
285
298 void
299 putData(uint32 stamp, const unsigned char* data = NULL, size_t len = 0);
300
313 void
314 sendImmediate(uint32 stamp, const unsigned char* data = NULL, size_t len = 0);
315
316
323 void setPadding(uint8 paddinglen)
324 { sendInfo.paddinglen = paddinglen; }
325
334 void setMark(bool mark)
335 { sendInfo.marked = mark; }
336
340 inline bool getMark() const
341 { return sendInfo.marked; }
342
353 size_t
354 setPartial(uint32 timestamp, unsigned char* data, size_t offset, size_t max);
355
356 inline microtimeout_t
358 { return defaultSchedulingTimeout; }
359
366 inline void
368 { schedulingTimeout = to; }
369
370 inline microtimeout_t
372 { return defaultExpireTimeout; }
373
381 inline void
383 { expireTimeout = to; }
384
386 { return expireTimeout; }
387
393 inline uint32
395 { return sendInfo.packetCount; }
396
402 inline uint32
404 { return sendInfo.octetCount; }
405
411 inline uint16
413 { return sendInfo.sendSeq; }
414
423 void
424 setOutQueueCryptoContext(CryptoContext* cc);
425
434 void
435 removeOutQueueCryptoContext(CryptoContext* cc);
436
445 getOutQueueCryptoContext(uint32 ssrc);
446
447
448 protected:
450
452 { }
453
455 {
458 OutgoingRTPPktLink* n) :
459 packet(pkt), prev(p), next(n) { }
460
461 ~OutgoingRTPPktLink() { delete packet; }
462
463 inline OutgoingRTPPkt* getPacket() { return packet; }
464
465 inline void setPacket(OutgoingRTPPkt* pkt) { packet = pkt; }
466
467 inline OutgoingRTPPktLink* getPrev() { return prev; }
468
469 inline void setPrev(OutgoingRTPPktLink* p) { prev = p; }
470
471 inline OutgoingRTPPktLink* getNext() { return next; }
472
473 inline void setNext(OutgoingRTPPktLink* n) { next = n; }
474
475 // the packet this link refers to.
477 // global outgoing packets queue.
479 };
480
488 void
489 dispatchImmediate(OutgoingRTPPkt *packet);
490
501 getSchedulingTimeout();
502
509 size_t
510 dispatchDataPacket();
511
520 inline void
521 setNextSeqNum(uint32 seqNum)
522 { sendInfo.sendSeq = seqNum; }
523
524 inline uint32
526 { return sendInfo.sendSeq; }
527
530 inline void
532 { initialTimestamp = ts; }
533
536 inline uint32
538 { return initialTimestamp; }
539
540 void purgeOutgoingQueue();
541
542 virtual void
543 setControlPeer(const InetAddress &host, tpport_t port) {}
544
545 #ifdef CCXX_IPV6
546 virtual void
547 setControlPeerIPV6(const IPV6Address &host, tpport_t port) {}
548 #endif
549
550 // The crypto contexts for outgoing SRTP sessions.
552 std::list<CryptoContext *> cryptoContexts;
553
554 private:
560 inline virtual void onExpireSend(OutgoingRTPPkt&)
561 { }
562
563 virtual void
564 setDataPeer(const InetAddress &host, tpport_t port) {}
565
566 #ifdef CCXX_IPV6
567 virtual void
568 setDataPeerIPV6(const IPV6Address &host, tpport_t port) {}
569 #endif
570
580 virtual size_t
581 sendData(const unsigned char* const buffer, size_t len) {return 0;}
582
583 #ifdef CCXX_IPV6
584 virtual size_t
585 sendDataIPV6(const unsigned char* const buffer, size_t len) {return 0;}
586 #endif
587
591 // outgoing data packets queue
594 // transmission scheduling timeout for the service thread
596 // how old a packet can reach in the sending queue before deletetion
598
599
600 struct {
601 // number of packets sent from the beginning
602 uint32 packetCount;
603 // number of payload octets sent from the beginning
604 uint32 octetCount;
605 // the sequence number of the next packet to sent
606 uint16 sendSeq;
607 // contributing sources
608 uint32 sendSources[16];
609 // how many CSRCs to send.
610 uint16 sendCC;
611 // pad packets to a paddinglen multiple
612 uint8 paddinglen;
613 // This flags tells whether to set the bit M in the
614 // RTP fixed header of the packet in which the next
615 // provided data will be sent.
616 bool marked;
617 // whether there was not loss.
618 bool complete;
619 // ramdonly generated offset for the timestamp of sent packets
620 uint32 initialTimestamp;
621 // elapsed time accumulated through successive overflows of
622 // the local timestamp field
623 timeval overflowTime;
624 } sendInfo;
625 };
626 // oqueue
628
629 #ifdef CCXX_NAMESPACES
630 }
631 #endif
632
633 #endif //CCXX_RTP_OQUEUE_H_
634
uint32 getSendPacketCount() const
Get the total number of packets sent so far.
Definition: oqueue.h:394
uint32 getSendOctetCount() const
Get the total number of octets (payload only) sent so far.
Definition: oqueue.h:403
void setMark(bool mark)
Set marker bit for the packet in which the next data provided will be send.
Definition: oqueue.h:334
virtual size_t sendData(const unsigned char *const buffer, size_t len)
This function performs the physical I/O for writing a packet to the destination.
Definition: oqueue.h:581
void setSchedulingTimeout(microtimeout_t to)
Set the default scheduling timeout to use when no data packets are waiting to be sent.
Definition: oqueue.h:367
bool getMark() const
Get wheter the mark bit will be set in the next packet.
Definition: oqueue.h:340
The implementation for a SRTP cryptographic context.
Definition: CryptoContext.h:76
ThreadLock destinationLock
Definition: oqueue.h:133
timeval overflowTime
Definition: oqueue.h:623
void writeLockDestinationList() const
Definition: oqueue.h:95
uint32 microtimeout_t
Time interval expressed in microseconds.
Definition: base.h:69
uint8 paddinglen
Definition: oqueue.h:612
uint32 getCurrentSeqNum(void)
Definition: oqueue.h:525
unsigned short tpport_t
Transport Protocol Ports.
Definition: address.h:86
std::list< TransportAddress * > destList
Definition: oqueue.h:71
microtimeout_t expireTimeout
Definition: oqueue.h:597
The Mutex class is used to protect a section of code so that at any given time only a single thread c...
Definition: thread.h:186
This class handles a list of destination addresses.
Definition: oqueue.h:68
void lockDestinationList() const
Definition: oqueue.h:88
microtimeout_t getDefaultExpireTimeout() const
Definition: oqueue.h:371
uint32 packetCount
Definition: oqueue.h:602
void setNextSeqNum(uint32 seqNum)
For thoses cases in which the application requires a method to set the sequence number for the outgoi...
Definition: oqueue.h:521
std::list< CryptoContext * > cryptoContexts
Definition: oqueue.h:552
TransportAddress * getFirstDestination() const
Definition: oqueue.h:85
uint32 getInitialTimestamp()
Definition: oqueue.h:537
virtual void onExpireSend(OutgoingRTPPkt &)
A hook to filter packets being sent that have been expired.
Definition: oqueue.h:560
void setPadding(uint8 paddinglen)
Set padding.
Definition: oqueue.h:323
#define InetHostAddress
Definition: address.h:76
uint32 initialTimestamp
Definition: oqueue.h:593
OutgoingRTPPktLink * sendLast
Definition: oqueue.h:592
Base classes for RTP queues.
microtimeout_t getDefaultSchedulingTimeout() const
Definition: oqueue.h:357
virtual void setControlPeer(const InetAddress &host, tpport_t port)
Definition: oqueue.h:543
The ThreadLock class impliments a thread rwlock for optimal reader performance on systems which have ...
Definition: thread.h:357
static const microtimeout_t defaultSchedulingTimeout
Definition: oqueue.h:588
const tpport_t DefaultRTPDataPort
registered default RTP data transport port
Definition: base.h:111
#define InetAddress
Definition: address.h:75
microtimeout_t schedulingTimeout
Definition: oqueue.h:595
void setInitialTimestamp(uint32 ts)
Definition: oqueue.h:531
tpport_t getControlTransportPort() const
Definition: oqueue.h:125
const InetAddress & getNetworkAddress() const
Definition: oqueue.h:119
#define __EXPORT
Definition: audio2.h:51
uint16 getSequenceNumber() const
Get the sequence number of the next outgoing packet.
Definition: oqueue.h:412
#define InetMcastAddress
Definition: address.h:78
tpport_t getDataTransportPort() const
Definition: oqueue.h:122
uint32 octetCount
Definition: oqueue.h:604
virtual ~OutgoingDataQueue()
Definition: oqueue.h:451
ThreadLock sendLock
Definition: oqueue.h:590
uint16 sendCC
Definition: oqueue.h:610
Mutex cryptoMutex
Definition: oqueue.h:551
static const microtimeout_t defaultExpireTimeout
Definition: oqueue.h:589
TransportAddress(InetAddress na, tpport_t dtp, tpport_t ctp)
Definition: oqueue.h:114
void setExpireTimeout(microtimeout_t to)
Set the "expired" timer for expiring packets pending in the send queue which have gone unsent and are...
Definition: oqueue.h:382
virtual void setDataPeer(const InetAddress &host, tpport_t port)
Definition: oqueue.h:564
bool isSingleDestination() const
Get whether there is only a destination in the list.
Definition: oqueue.h:82
A generic outgoing RTP data queue supporting multiple destinations.
Definition: oqueue.h:222
microtimeout_t getExpireTimeout() const
Definition: oqueue.h:385
RTP packets being sent.
Definition: rtppkt.h:510
void unlockDestinationList() const
Definition: oqueue.h:91
uint16 sendSeq
Definition: oqueue.h:606 | __label__pos | 0.7897 |
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.
I use CakePHP's built-in method $this->RequestHandler->isMobile() to detect mobile device, but it didn't work when I wanted to try my app using desktop browser. So I use this following code, since its url starts with 'm.' for example 'm.mywebsite.com':
<?php
$url = explode('.', $_SERVER['SERVER_NAME']);
if($url[0] == 'm'){
echo "Welcome to our mobile version";
}
?>
But somehow it also didn't work when tested on another server that has subdomain address like 'm.trial.mywebsite2.com'. Is there any other better detection code for this kind of web address?
share|improve this question
closed as not a real question by hakre, casperOne Nov 2 '12 at 13:47
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center. If this question can be reworded to fit the rules in the help center, please edit the question.
1
What is returned if you add echo $url[0]; to your code? – bergie3000 Nov 2 '12 at 4:17
In my localhost, 'm.localhost.com', returns 'm'. but in another server, 'm.trial.xxxxx.com' it returns 'trial'. – abdgstywn Nov 2 '12 at 4:23
1 Answer 1
Use Regular Expression, or simply strpos() it.
// Regular Expression
if (preg_match('/^m\./', $_SERVER['SERVER_NAME']) {
}
// strpos()
if (0 === strpos($_SERVER['SERVER_NAME'], 'm.')) {
}
Your situation smells like there is something wrong in $_SERVER['SERVER_NAME'], you should really give it a check.
share|improve this answer
you're right, but I think it's better to use $_SERVER['HTTP_HOST'] instead of $_SERVER['SERVER_NAME'] – abdgstywn Nov 2 '12 at 6:00
Property HTTP_HOST rely solely on request/response headers to appear in $_SERVER, which at least requires a proper configuration on server side. Use it with care. – Vicary Nov 2 '12 at 6:06
Not the answer you're looking for? Browse other questions tagged or ask your own question. | __label__pos | 0.545578 |
TextBoxBase::Multiline Property
Gets or sets a value indicating whether this is a multiline text box control.
Namespace: System.Windows.Forms
Assembly: System.Windows.Forms (in System.Windows.Forms.dll)
public:
property bool Multiline {
virtual bool get();
virtual void set(bool value);
}
Property Value
Type: System::Boolean
true if the control is a multiline text box control; otherwise, false. The default is false.
A multiline text box allows you to display more than one line of text in the control. If the WordWrap property is set to true, text entered into the multiline text box is wrapped to the next line in the control. If the WordWrap property is set to false, text entered into the multiline text box control will be displayed on the same line until a newline character is entered.
The following can be used as newline characters:
You can add scroll bars to a text box using the ScrollBars property to display horizontal and/or vertical scroll bars. This allows the user to scroll through the text that extends beyond the dimensions of the control.
System_CAPS_noteNote
Because the default value of the Multiline property is false, the default size of a TextBox will be in accordance with the font size even if you resize the TextBox. To get a consistent size for your TextBox, set its Multiline property to true.
System_CAPS_noteNote
On Japanese operating systems, if the Multiline property is set to true, setting the PasswordChar property will display the text of the password, thus compromising system security. Therefore, on Japanese operating systems, set the Multiline property to false if you set the PasswordChar property.
System_CAPS_noteNote
This property is set to false by default for all derived classes, with the exception of the RichTextBox control.
For a RichTextBox control, the RichTextBox::Multiline property affects whether or not the control will automatically resize, as follows:
The following code example uses TextBox, a derived class, to create a multiline TextBox control with vertical scroll bars. This example also uses the AcceptsTab, AcceptsReturn, and WordWrap properties to make the multiline text box control useful for creating text documents.
public:
void CreateMyMultilineTextBox()
{
// Create an instance of a TextBox control.
TextBox^ textBox1 = gcnew TextBox;
// Set the Multiline property to true.
textBox1->Multiline = true;
// Add vertical scroll bars to the TextBox control.
textBox1->ScrollBars = ScrollBars::Vertical;
// Allow the RETURN key in the TextBox control.
textBox1->AcceptsReturn = true;
// Allow the TAB key to be entered in the TextBox control.
textBox1->AcceptsTab = true;
// Set WordWrap to true to allow text to wrap to the next line.
textBox1->WordWrap = true;
// Set the default text of the control.
textBox1->Text = "Welcome!" + Environment::NewLine + "Second Line";
}
.NET Framework
Available since 1.1
Return to top
Show: | __label__pos | 0.986217 |
J.E.D.
I
Introduction to Programming I
Version 1.0 May 2005
Introduction to Programming I
1
J.E.D.I
Author Florence Tiu Balagtas Team Joyce Avestro Florence Balagtas Rommel Feria Reginald Hutcherson Rebecca Ong John Paul Petines Sang Shin Raghavan Srinivas Matthew Thompson
Requirements For the Laboratory Exercises
Minimum Hardware Configuration • Microsoft Windows operating systems:
• • • • • • • • • • • • • • • • • •
Processor: 500 MHz Intel Pentium III workstation or equivalent Memory: 384 megabytes Disk space: 125 megabytes of free disk space Processor: 450 MHz UltraTM 10 workstation or equivalent Memory: 384 megabytes Disk space: 125 megabytes of free disk space Processor: 500 MHz Intel Pentium III workstation or equivalent Memory: 384 megabytes
SolarisTM operating system:
Linux operating system:
Disk space: 125 megabytes of free disk space Recommended Hardware Configuration • Microsoft Windows operating systems: Processor: 780 MHz Intel Pentium III workstation or equivalent Memory: 512 megabytes Disk space: 125 megabytes of free disk space Processor: 500 MHz UltraTM 60 workstation or equivalent Memory: 512 megabytes Disk space: 125 megabytes of free disk space Processor: 800 MHz Intel Pentium III workstation or equivalent Memory: 512 megabytes
SolarisTM operating system:
Linux operating system:
Disk space: 125 megabytes of free disk space Operating System NetBeans IDE runs on operating systems that support the JavaTM VM. Below is a list of platforms that NetBeans IDE has been tested on. • Microsoft Windows XP Professional SP1
• • • • • • • • •
Microsoft Windows 2000 Professional SP3 Solaris operating system (SPARC® Platform Edition), versions 8, 9, and 10 Solaris operating system (x86 Platform Edition), versions 8, 9, and 10 Red Hat Linux 9.0 Red Hat Enterprise Linux 3
Sun Java Desktop System NetBeans IDE is also known to run on the following platforms: • Various other Linux distributions Mac OS X 10.1.1 or later Open VMS 7.2-1 or later
Other UNIX ® platforms, such as HP-UX Software NetBeans IDE runs on the J2SE JDK 5.0 (JavaTM 2 JDK, Standard Edition), which consists of the Java Runtime Environment plus developers tools for compiling, debugging, and running applications written in the JavaTM language. NetBeans IDE 4.0 has also been tested on J2SE SDK version 1.4.2. For more information, please visit: http://www.netbeans.org/community/releases/40/relnotes.html
Introduction to Programming I
2
J.E.D.I
Revision History
For Version 1.1 August 2005 Section Version Number Revision History Appendix E: Hands-on Lab Exercises
Details Change from 1.0 to 1.1 Added Added (c/o Sang)
Chapter 10: Creating Your own classes Added subsection on How to set classpath at packages section Chapter 11: Inheritance, Interfaces Polymorphism section and Polymorphism • Added example that uses another class whose method can receive a reference variable Interface • Added sections • Why do we use Interfaces? • Interface vs. Abstract Class • Interface vs. Class • Relationship of an Interface to a Class • Inheritance among Interfaces
Introduction to Programming I
3
J.E.D.I
Table of Contents
1 Introduction to Computer Programming.............................................................. 11 1.1 Objectives............................................................................................... 11 1.2 Introduction............................................................................................. 11 1.3 Basic Components of a Computer................................................................ 12 1.3.1 Hardware.......................................................................................... 12 1.3.1.1 The Central Processing Unit.......................................................... 12 1.3.1.2 Memory .................................................................................... 12 1.3.1.3 Input and Output Devices............................................................. 13 1.3.2 Software........................................................................................... 13 1.4 Overview of Computer Programming Languages........................................... 14 1.4.1 What is a Programming Language?....................................................... 14 1.4.2 Categories of Programming Languages.................................................. 14 1.5 The Program Development Life Cycle........................................................... 15 1.5.1 Problem Definition............................................................................. 16 1.5.2 Problem Analysis............................................................................... 16 1.5.3 Algorithm design and representation.................................................... 17 1.5.3.1 Flowcharting Symbols and their meanings...................................... 18 1.5.4 Coding and Debugging....................................................................... 19 1.6 Number Systems and Conversions.............................................................. 20 1.6.1 Decimal............................................................................................ 20 1.6.2 Binary.............................................................................................. 20 1.6.3 Octal................................................................................................ 20 1.6.4 Hexadecimal..................................................................................... 20 1.6.5 Conversions...................................................................................... 21 1.6.5.1 Decimal to Binary / Binary to Decimal............................................ 21 1.6.5.2 Decimal to Octal (or Hexadecimal)/Octal (or Hexadecimal) to Decimal.... 22 1.6.5.3 Binary to Octal / Octal to Binary.................................................... 23 1.6.5.4 Binary to Hexadecimal / Hexadecimal to Binary............................... 24 1.7 Exercises................................................................................................. 25 1.7.1 Writing Algorithms............................................................................. 25 1.7.2 Number Conversions.......................................................................... 25 2 Introduction to Java........................................................................................ 26 2.1 Objectives............................................................................................... 26 2.2 Java Background...................................................................................... 26 2.2.1 A little Bit of History .......................................................................... 26 2.2.2 What is Java Technology?................................................................... 26 2.2.2.1 A programming language............................................................. 26 2.2.2.2 A development environment......................................................... 26 2.2.2.3 An application environment.......................................................... 26 2.2.2.4 A deployment environment........................................................... 27 2.2.3 Some Features of Java........................................................................ 27 2.2.3.1 The Java Virtual Machine.............................................................. 27 2.2.3.2 Garbage Collection...................................................................... 27 2.2.3.3 Code Security............................................................................. 28 2.2.4 Phases of a Java Program.................................................................... 29 3 Getting to know your Programming Environment................................................. 30 3.1 Objectives............................................................................................... 30 3.2 Introduction............................................................................................. 30
Introduction to Programming I
4
J.E.D.I
3.3 My First Java Program............................................................................... 30 3.4 Using a Text Editor and Console................................................................. 31 3.4.1 Errors .............................................................................................. 46 3.4.1.1 Syntax Errors............................................................................. 46 3.4.1.2 Run-time Errors.......................................................................... 47 3.5 Using Netbeans........................................................................................ 48 3.6 Exercises................................................................................................. 66 3.6.1 Hello World!...................................................................................... 66 3.6.2 The Tree........................................................................................... 66 4 Programming Fundamentals............................................................................. 67 4.1 Objectives............................................................................................... 67 4.2 Dissecting my first Java program................................................................ 67 4.3 Java Comments........................................................................................ 69 4.3.1 C++-Style Comments......................................................................... 69 4.3.2 C-Style Comments............................................................................. 69 4.3.3 Special Javadoc Comments................................................................. 69 4.4 Java Statements and blocks....................................................................... 70 4.5 Java Identifiers........................................................................................ 71 4.6 Java Keywords......................................................................................... 72 4.7 Java Literals............................................................................................ 73 4.7.1 Integer Literals ................................................................................. 73 4.7.2 Floating-Point Literals ........................................................................ 73 4.7.3 Boolean Literals ................................................................................ 73 4.7.4 Character Literals .............................................................................. 74 4.7.5 String Literals ................................................................................... 74 4.8 Primitive data types.................................................................................. 75 4.8.1 Logical - boolean............................................................................... 75 4.8.2 Textual – char................................................................................... 75 4.8.3 Integral – byte, short, int & long.......................................................... 76 4.8.4 Floating Point – float and double.......................................................... 77 4.9 Variables................................................................................................. 78 4.9.1 Declaring and Initializing Variables....................................................... 78 4.9.2 Outputting Variable Data.................................................................... 79 4.9.3 System.out.println() vs. System.out.print() ......................................... 79 4.9.4 Reference Variables vs. Primitive Variables............................................ 80 4.10 Operators.............................................................................................. 81 4.10.1 Arithmetic operators......................................................................... 81 4.10.2 Increment and Decrement operators................................................... 84 4.10.3 Relational operators......................................................................... 86 4.10.4 Logical operators.............................................................................. 89 4.10.4.1 && (logical AND) and & (boolean logical AND)............................... 90 4.10.4.2 || (logical OR) and | (boolean logical inclusive OR)......................... 92 4.10.4.3 ^ (boolean logical exclusive OR).................................................. 94 4.10.4.4 ! (logical NOT).......................................................................... 95 4.10.5 Conditional Operator (?:).................................................................. 96 4.10.6 Operator Precedence........................................................................ 98 4.11 Exercises............................................................................................... 99 4.11.1 Declaring and printing variables......................................................... 99 4.11.2 Getting the average of three numbers................................................. 99 4.11.3 Output greatest value....................................................................... 99 4.11.4 Operator precedence........................................................................ 99 5 Getting Input from the Keyboard..................................................................... 100 5.1 Objectives............................................................................................. 100
Introduction to Programming I
5
J.E.D.I
6
7
8
9
5.2 Using BufferedReader to get input............................................................. 100 5.3 Using JOptionPane to get input................................................................. 104 5.4 Exercises............................................................................................... 106 5.4.1 Last 3 words (BufferedReader version)................................................ 106 5.4.2 Last 3 words (JOptionPane version).................................................... 106 Control Structures......................................................................................... 107 6.1 Objectives............................................................................................. 107 6.2 Decision Control Structures...................................................................... 107 6.2.1 if statement.................................................................................... 107 6.2.2 if-else statement.............................................................................. 109 6.2.3 if-else-if statement........................................................................... 111 6.2.4 Common Errors when using the if-else statements:............................... 112 6.2.5 Example for if-else-else if.................................................................. 113 6.2.6 switch statement............................................................................. 114 6.2.7 Example for switch........................................................................... 116 6.3 Repetition Control Structures.................................................................... 117 6.3.1 while loop....................................................................................... 117 6.3.2 do-while loop................................................................................... 119 6.3.3 for loop........................................................................................... 120 6.4 Branching Statements............................................................................. 121 6.4.1 break statement.............................................................................. 121 6.4.1.1 Unlabeled break statement......................................................... 121 6.4.1.2 Labeled break statement............................................................ 122 6.4.2 continue statement.......................................................................... 123 6.4.2.1 Unlabeled continue statement..................................................... 123 6.4.2.2 Labeled continue statement........................................................ 123 6.4.3 return statement.............................................................................. 124 6.5 Exercises............................................................................................... 125 6.5.1 Grades........................................................................................... 125 6.5.2 Number in words.............................................................................. 125 6.5.3 Hundred Times................................................................................ 125 6.5.4 Powers........................................................................................... 125 Java Arrays.................................................................................................. 126 7.1 Objectives............................................................................................. 126 7.2 Introduction to arrays.............................................................................. 126 7.3 Declaring Arrays..................................................................................... 127 7.4 Accessing an array element...................................................................... 129 7.5 Array length........................................................................................... 130 7.6 Multidimensional Arrays........................................................................... 131 7.7 Exercises............................................................................................... 132 7.7.1 Days of the Week............................................................................. 132 7.7.2 Greatest number.............................................................................. 132 7.7.3 Addressbook Entries......................................................................... 132 Command-line Arguments.............................................................................. 133 8.1 Objectives............................................................................................. 133 8.2 Command-line arguments........................................................................ 133 8.3 Command-line arguments in Netbeans...................................................... 135 8.4 Exercises............................................................................................... 139 8.4.1 Print arguments............................................................................... 139 8.4.2 Arithmetic Operations....................................................................... 139 Working with the Java Class Library................................................................. 140 9.1 Objectives............................................................................................. 140 9.2 Introduction to Object-Oriented Programming............................................. 140
Introduction to Programming I
6
J.E.D.I
9.3 Classes and Objects................................................................................ 141 9.3.1 Difference Between Classes and Objects.............................................. 141 9.3.2 Encapsulation.................................................................................. 142 9.3.3 Class Variables and Methods.............................................................. 142 9.3.4 Class Instantiation........................................................................... 143 9.4 Methods................................................................................................ 144 9.4.1 What are Methods and Why Use Methods?........................................... 144 9.4.2 Calling Instance Methods and Passing Variables....................................145 9.4.3 Passing Variables in Methods............................................................. 146 9.4.3.1 Pass-by-value........................................................................... 146 9.4.3.2 Pass-by-reference...................................................................... 147 9.4.4 Calling Static Methods...................................................................... 148 9.4.5 Scope of a variable........................................................................... 149 9.5 Casting, Converting and Comparing Objects............................................... 152 9.5.1 Casting Primitive Types..................................................................... 152 9.5.2 Casting Objects............................................................................... 154 9.5.3 Converting Primitive Types to Objects and Vice Versa............................ 156 9.5.4 Comparing Objects........................................................................... 157 9.5.5 Determining the Class of an Object..................................................... 159 9.6 Exercises............................................................................................... 160 9.6.1 Defining terms................................................................................. 160 9.6.2 Java Scavenger Hunt........................................................................ 160 10 Creating your own Classes............................................................................ 161 10.1 Objectives............................................................................................ 161 10.2 Defining your own classes...................................................................... 162 10.3 Declaring Attributes.............................................................................. 163 10.3.1 Instance Variables.......................................................................... 163 10.3.2 Class Variables or Static Variables.................................................... 164 10.4 Declaring Methods................................................................................ 164 10.4.1 Accessor methods........................................................................... 165 10.4.2 Mutator Methods............................................................................ 166 10.4.3 Multiple Return statements.............................................................. 167 10.4.4 Static methods............................................................................... 167 10.4.5 Sample Source Code for StudentRecord class..................................... 168 10.5 The this reference................................................................................. 170 10.6 Overloading Methods............................................................................. 171 10.7 Declaring Constructors........................................................................... 173 10.7.1 Default Constructor........................................................................ 173 10.7.2 Overloading Constructors................................................................ 173 10.7.3 Using Constructors......................................................................... 174 10.7.4 The this() Constructor Call............................................................... 175 10.8 Packages............................................................................................. 176 10.8.1 Importing Packages........................................................................ 176 10.8.2 Creating your own packages............................................................ 176 10.8.3 Setting the CLASSPATH.................................................................. 177 10.9 Access Modifiers................................................................................... 179 10.9.1 default access (also called package accessibility)................................ 179 10.9.2 public access................................................................................. 179 10.9.3 protected access............................................................................ 180 10.9.4 private access................................................................................ 180 10.10 Exercises........................................................................................... 181 10.10.1 Address Book Entry....................................................................... 181 10.10.2 AddressBook................................................................................ 181
Introduction to Programming I
7
.......................... 200 12..................................3 Output greatest value......................................................................... Polymorphism and Interfaces...............6.................... 240 Using Netbeans................... 182 11...............................4 Operator precedence...................6.....................1 Objectives...................................................... 257 Chapter 3 Exercises.........................................................2 Interface vs................... 251 1........4 Exercises.I 11 Inheritance........................2................................................. 196 12 Basic Exception Handling.... 241 Appendix C : Answers to Exercises............................................. 213 Installing Netbeans in Windows............................... 197 12...........................................................1 Hello World!............... 201 Installing Java in Linux.......... 202 Installing Java in Windows................................................................................ Abstract Class................................................................ 262 Chapter 6 Exercises..... 251 Chapter 1 Exercises........................4 Final Methods and Final Classes.................................................5....2 What are Exceptions?................................................. 258 3.............................................................................2 Last 3 words (JOptionPane version)...............2 Number Conversions.................................................................... 260 4..........................5........................3 Handling Exceptions.......................... 183 11........1 Writing Algorithms.............................................................5 Interfaces.................................................... 195 11................................................2 Getting the average of three numbers......................... 227 Setting the Path...............................................1 Objectives.................4.........2 Catching Exceptions 2...............................E....................D................................................................................3 Overriding Methods................................... 192 11.......5 Relationship of an Interface to a Class.................................................... 259 4.......... 258 3..................................2 The Shape abstract class............................ 182 11............. 259 4...........J.....................................................2 The Tree.............2 The super keyword.............. 261 5..............5.................................................................... 261 5....... 259 4..................................................................................4 Creating Interfaces.........1 Catching Exceptions1................................ 190 11.........................5.............1 Extending StudentRecord............................................................................................ 196 11...........................................................................................................................................................................................................5................4 Abstract Classes......................................1 Declaring and printing variables........................................................................ 263 Introduction to Programming I 8 ..................2 Inheritance.............................................................................................................1 Last 3 words (BufferedReader version)... 251 1..........................................................1 Why do we use Interfaces?.6 Inheritance among Interfaces................. 222 Appendix B: Getting to know your Programming Environment (Windows XP version).................. 196 11...................................6 Exercises............................................ 197 12.3 Polymorphism................................... Class......................... 200 12.............2........... 195 11........................................... 254 Chapter 2 (No exercises).................................................................................... 192 11.................................................... 200 Appendix A : Java and Netbeans Installation................................................................. 193 11................................................................................................................. 182 11......... 188 11.......................................................... 197 12...............................2...................................................................... 226 My First Java Program.................................................5................ 226 Using a Text Editor and Console..............................................................................................................1 Defining Superclasses and Subclasses...................2............................... 193 11......................... 187 11....................................................................................................4....................................3 Interface vs............................................. 260 Chapter 5 Exercises.................................. 185 11........................ 186 11......... 192 11..... 258 Chapter 4 Exercises............ 210 Installing Netbeans in Linux.................. 197 12...................
...................... 289 12............................................. 304 7........ 316 Chapter 11 Hands-on.........................................................................................................................................................2 Catching Exceptions 2........................................ 301 5...........................2 Conditional Operator......... 303 6.............................4 Powers........................ 289 12.....................................................2 Greatest number..............................................1 Defining terms..................................................................................................................................................... 296 3........ 297 3.. 307 Chapter 10 Hands-on................................................................1 Catching Exceptions 1.........................1 For Loop....................................................................................... 267 6................ 308 10.................... 301 5......2 Java Scavenger Hunt........................................1 Grades .................... 275 Chapter 9 Exercises.................................................................................................................................I 6...................... 304 Chapter 8 Hands-on.....................................................................................................................................................................................................2 Getting Input From Keyboard via JOptionPane................... 299 4....................................................................1 Address Book Entry........D..........................1 Pass-by-Value....... Initializing........................................................................2 AddressBook.................................................................................2 Number in words................ 294 Appendix E : Hands-on Laboratory.................. 300 Chapter 5 Hands-on.................................................................... 276 9...2 Abstract Classes.3 Packaging...................3 Write......................................1 Declaring............... 305 9...............1 Print Arguments........................................ 295 Chapter 2 Hands-on...........................................................................................1 Create your own class....................... 270 Chapter 7 Exercises............................................1 Extending StudentRecord.....................3 Hundred Times................................................................... 308 10.....1 Things to check before you start the lab .........................................................................................1 Arrays...........................................2 Overloading............. 276 9.................... Printing Variables................................2 Pass-by-Reference...................................................................................................................................................................................................................................................................J..................................................... Compile............................3 Comparing Objects......................................... 284 11......................................................................................................... 279 Chapter 11 Exercises................................................................................2 Write.................................................... 292 Machine Problem 2: Minesweeper.............................................................................................. 276 Chapter 10 Exercises........................................................................................................................................ 298 Chapter 4 Hands-on.... Compile............................................ 295 Chapter 1 Hands-on...........................1 Getting Input From Keyboard via BufferedReader......................... 302 Chapter 6 Hands-on............................. 277 10......... 299 4................................... 293 Machine Problem 3: Number Conversion......E........................................ and Run Hello Java Program.. and Run Hello Java Program using NetBeans................................................................................ 284 11.................................... 287 Chapter 12 Exercises............................................................ 305 Chapter 9 Hands-on.................................................. 289 Appendix D : Machine Problems.................... 305 9......................................... 273 7........................................................................................ 313 10...................... 321 Introduction to Programming I 9 ................ 306 9.......... 274 Chapter 8 Exercises............................. 292 Machine Problem 1: Phone Book.. 265 6.................. 275 8....... 273 7.... 277 10.......................................................................1 Days of the Week..... 295 Note to the Teacher.................................................................................. 296 3............................................................................................................................................. 303 Chapter 7 Hands-on................ 263 6................... 295 Chapter 3 Hands-on...............................................
...........Overriding..................................................................3 Polymorphism.................................... 349 Answers to Hands-on Exercises...3 Packaging.......Overriding..... 362 Introduction to Programming I 10 .........................................................................E..........5 Interfaces 1................................................................................................................................1 Exception Handling.......I 11.......................................1 Create your own class. 354 11.........................................................................................2 Inheritance .......1 Inheritance – Constructor.................................................................... 326 11......... 321 11...............................................................................................J........................ 352 10............................ 344 Chapter 12 Hands-on............. 358 11......................................................................................3 Polymorphism............... 360 11...............................D...6 Interfaces 2.................4 Abstract Classes..................... 350 10..........................................................6 Interfaces 2. 337 11............. 349 12.....................2 Inheritance ........2 Overloading...........5 Interfaces 1........................................................ 357 11.................................................................................. 355 11.... 330 11..................................................................................................................................................................................................4 Abstract Classes........................................... 350 10.............1 Inheritance – Constructor..... 355 11..................... 340 11.................................
Finally. It is a data processing machine which accepts data via an input device and its processor manipulates the data according to a program. At the end of the lesson. The second major component is the software which is the intangible part of a computer. different number systems and conversions from one type to another will be discussed. Introduction to Programming I 11 . we will be discussing the basic components of a computer. both hardware and software.1 Objectives In this section.E.I 1 Introduction to Computer Programming 1.J. It consists of data and the computer programs. It is composed of electronic and mechanical parts.D. The computer has two major components.2 Introduction A computer is a machine that performs a variety of tasks according to specific instructions. The first one is the Hardware which is the tangible part of the computer. the student should be able to: • • • • Identify the different components of a computer Know about programming languages and their categories Understand the program development life cycle and apply it in problem solving Learn the different number systems and their conversions 1. We will also be giving a brief overview of programming languages and the program development life cycle.
2 Memory The memory is where data and instructions needed by the CPU to do its appointed tasks can be found. It is used to hold programs and data.1. It is sometimes called the RAM (Random Access Memory). It is not used for long-term storage. all information residing in the main memory is erased. The CPU accesses the memory with the use of these addresses. It contains millions of extremely tiny electrical parts. The computer's main memory is considered as volatile storage. Examples of processors are Pentium. It is used to hold programs and data for long term use. It is divided into several storage locations which have corresponding addresses. Main Memory Fast Expensive Low Yes Secondary Memory Slow Cheap High No Property Speed Price Capacity Volatile Table 1: Comparison between main memory and secondary memory Introduction to Programming I 12 .E. This means that once the computer is turned off.I 1. that the processor is actively working with.3.3. 1. Athlon and SPARC.1. The Secondary Memory The secondary memory is connected to main memory. 2. Secondary memory is considered as non-volatile storage.3.J. It does the fundamental computing within the system. 1.1 The Central Processing Unit The processor is the “brain” of the computer. This means that information residing in secondary memory is not erased after the computer is turned off. Examples of secondary memory are hard disks and cd-rom.1 Hardware 1.3 Basic Components of a Computer 1.D. Main Memory The main memory is very closely connected to the processor.
Machine language is in the form of ones and zeros. Windows. It is kept on some hardware device like a hard disk. Unix. printers and speakers.D. The data that the computer uses can be anything that a program needs.J. for this purpose.1.3 Input and Output Devices Input and output devices allows a computer system to interact with the outside world by moving data into and out of the system. Solaris. Introduction to Programming I 13 . 1. there exists compilers.E. Examples of input devices are keyboards.3. Some Types of Computer Programs: 1. Since it is highly impractical for people to create programs out of zeros and ones. there must be a way of translating or converting a language which we understand into machine language.I 1. Compilers • The computer understands only one language: machine language. MacOS 2. Systems Programs • • Programs that are needed to keep all the hardware and software systems running together smoothly Examples: • Operating Systems like Linux. Examples of output devices are monitors. Programs acts like instructions for the processor. Application Programs • • Programs that people use to get their work done Examples: • Word Processor • Game programs • Spreadsheets 3.2 Software A software is the program that a computer uses in order to function. mice and microphones. but it itself is intangible.3.
Examples are Java. but they are much easier to program in because they allow a programmer to substitute names for numbers. C. Originally. but regardless of what language you use. how these data will be stored/transmitted.2 Categories of Programming Languages 1. etc. these instructions are translated into machine language that can be understood by computers.1 What is a Programming Language? A programming language is a standardized communication technique for expressing instructions to a computer.4. Many programmers today might refer to these latter languages as low-level. each language has its own syntax and grammar. There are different types of programming languages that can be used to create programs. C++. Programming languages enable a programmer to precisely specify what data a computer will act upon. Assembly languages are available for each CPU family.E. and each assembly instruction is translated into one machine instruction by an assembler program.D.4 Overview of Computer Programming Languages 1. assembly language was considered low-level and COBOL. Fortran • 2. Introduction to Programming I 14 . and abstract from low-level computer processor operations such as memory accesses. Low-level Assembly Language • Assembly languages are similar to machine languages. Like human languages.4. High-level Programming Languages • A high-level programming language is a programming language that is more userfriendly. were considered high-level. A programming statement may be translated into one or several machine instructions by a compiler. and precisely what actions to take under various circumstances.I 1. C. to some extent platform-independent.J. Basic. 1. Note: The terms "high-level" and "low-level" are inherently relative.
let us define a single problem that we will solve step-by-step as we discuss the problem solving methodologies in detail. they follow an organized plan or methodology.E. Problem Definition Problem Analysis Algorithm design and representation (Pseudocode or flowchart) Coding and debugging In order to understand the basic steps in solving a problem on a computer. The problem we will solve will be defined in the next section.5 The Program Development Life Cycle Programmers do not sit down and start writing code right away when trying to make a computer program. 3. Instead. Here are the basic steps in trying to solve a problem on the computer: 1.D.J. that breaks the process into a series of tasks. Introduction to Programming I 15 . 2. 4.I 1.
Usually.2 Problem Analysis After the problem has been adequately defined. the problem must be well and clearly defined first in terms of its input and output requirements.I 1.E.D. this step involves breaking up the problem into smaller and simpler subproblems. the simplest and yet the most efficient and effective approach to solve the problem must be formulated.J. Let us now define our example problem: “Create a program that will determine the number of times a name occurs in a list. Before a program can be designed to solve a particular problem. name to look for Output of the program: the number of times the name occurs in a list Introduction to Programming I 16 . Computer programming requires us to define the problem first before we even try to create a solution. Example Problem: Determine the number of times a name occurs in a list Input to the program: list of names.1 Problem Definition A programmer is usually given a task in the form of a problem.5.” 1.5. A clearly defined problem is already half the solution.
it is normally required to express our solution in a step-by-step manner. let's call this the keyname 3. we can now set to finding a solution. Now given the problem defined in the previous sections. Compare the keyname to each of the names in the list 4. which is a cross between human language and a programming language. An Algorithm is a clear and unambiguous specification of the steps needed to solve a problem.D.3 Algorithm design and representation Once our problem is clearly defined. Get the name to look for.E. It may be expressed in either Human language (English. Get the list of names 2. through a graphical representation like a flowchart or through a pseudocode. If all the names have been compared.5.1: Example of a flow chart Introduction to Programming I 17 . In computer programming. If the keyname is the same with a name in the list.J. output the result Expressing our solution through a flowchart: YES Figure 1. how do we express our general solution in such a way that it is simple yet understandable? Expressing our solution through Human language: 1. Tagalog). add 1 to the count 5.I 1.
3. Decision Symbol Terminal Symbol Represents the beginning. and the arrowheads are mandatory only for right-to-left and bottom-totop flow.J. Annotation Symbol Represents a decision that determines which of a number of alternative paths is to be followed. Represents an I/O function.I Expressing our solution through pseudocode: Let nameList = List of Names Let keyName = the name to be sought Let Count = 0 For each name in NameList do the following if name == keyName Count = Count + 1 Display Count Figure 1. comments. Represents the addition of descriptive information. they state the concept in English or mathematical notation. You can use any symbols in creating your flowcharts. or on the right. form.1 Flowcharting Symbols and their meanings A flowchart is a design tool used to graphically represent the logic in a solution. Input/Output (I/O) Symbol Represents the sequence of available information and executable operations. Here are some guidelines for commonly used symbols in creating flowcharts. Also functions as the default symbol when no other symbol is available. or explanatory notes as clarification. as shown.E.2: Example of a pseudocode 1. as long as you are consistent in using them. or a point of interruption or delay in a program. Symbol Name Meaning Represents the process of executing a defined operation or groups of operations that results in a Process Symbol change in value. which makes data available for processing (input) or displaying (output)of processed information. The vertical line and the broken line may be placed on the left.5.D. Rather. the end. Flowcharts typically do not display programming language commands. or location of information.The lines connect Flowline Symbol other symbols. Introduction to Programming I 18 .
the programmer is unable to form an executable that a user can run until the error is fixed. The programmer has to add some fixes to the program in case of errors (also called bugs) that occurs in the program.E. This is especially true for logic errors such as infinite loops. the program compiles fine into an executable file.4 Coding and Debugging After constructing the algorithm. the program (or even their whole computer) freezes up due to an infinite loop. Also serves as an off-page connector. the program isn't 100% working right away.J. For example.D. However. Introduction to Programming I 19 . Forgetting a semi-colon at the end of a statement or misspelling a certain command. This type of error is called runtime error. In such a case. It's something the compiler can detect as an error. and unfortunately. and therefore. Other types of run-time errors are when an incorrect value is computed. Compilers aren't perfect and so can't catch all errors at compile time. is a compile-time error. Using the algorithm as basis. it is now possible to create the source code. Most of the time.I Symbol Name Connector Symbol Meaning Represents any entry from. Predefined Process Symbol Represents a named process consisting of one or more operations or program steps that are specified elsewhere. when the end-user runs the program. another part of the flowchart. The first one is compile-time error.5. Compile-Time Errors occur if there is a syntax error in the code. Table 2: Flowchart Symbols 1. This process of is called debugging. the same piece of code keeps executing over and over again infinitely so that it loops. The compiler will detect the error and the program won't even compile. But when you follow the code's logic. the source code can now be written using the chosen programming language. At this point. for example. and the other is runtime error. There are two types of errors that a programmer will encounter along the way. etc. the actual syntax of the code looks okay. or exit to. after the programmer has written the program. compilers aren't really smart enough to catch all of these types of errors at compile-time. the wrong thing happens.
Numbers in decimal form are in base 10. We need to write the subscript 16 to indicate that the number is a hexadecimal number.E. This means that the only legal digits are 0 and 1. lowercase or uppercase does not matter).J. Here are examples of numbers written in decimal form: 12610 (normally written as just 126) 1110 (normally written as just 11) 1.2 Binary Numbers in binary form are in base 2.D. This means that the only legal digits are 0-7.I 1.4 Hexadecimal Numbers in hexadecimal form are in base 16. The representation depends on what is called the BASE. Here are examples of numbers written in octal form: 1768 138 1. We need to write the subscript 8 to indicate that the number is an octal number. Here are examples of numbers written in hexadecimal form: 7E16 B16 Hexadecimal Decimal Equivalent 0 0 1 1 2 2 3 3 4 4 5 5 6 6 7 7 8 8 9 A B C D E F 1 9 10 11 12 13 14 5 Table 3: Hexadecimal Numbers and their Equivalence to decimal numbers Decimal 12610 1110 Binary 11111102 10112 Octal 1768 138 Hexadecimal 7E16 B16 Table 4: Summary of Examples Introduction to Programming I 20 .6.6. We need to write the subscript 2 to indicate that the number is a binary number.3 Octal Numbers in octal form are in base 8. The following are the four most common representations. This means that the only digits that appear are 0-9.6. 1. Here are examples of numbers written in binary form: 11111102 10112 1.1 Decimal We normally represent numbers in their decimal form.6. This means that the only legal digits are 09 and the letters A-F (or a-f.6 Number Systems and Conversions Numbers can be represented in a variety of ways.
and the result is the binary form of the number. Get the quotient and divide that number again by 2 and repeat the whole process until the quotient reaches 0 or 1. NOTE: For the last digit which is already less than the divisor (which is 2) just copy the value to the remainder portion. continuously divide the number by 2 and get the remainder (which is either 0 or 1). We then add all the products to get the resulting decimal number. For Example: 11111102 = ? Position Write it this way 10 Binary Digits 6 5 4 3 2 1 0 1 1 1 1 1 1 0 0 x 20 = 0 1 x 21 = 2 1 x 22 = 4 1 x 23= 8 1 x 24= 16 1 x 25 = 32 1 x 26 = 64 TOTAL: 126 Introduction to Programming I 21 . We then get all the remainders starting from the last remainder. writing the remainders from the bottom up.D.5 Conversions 1.E. and get that number as a digit of the binary form of the number. we get the binary number 11111102 To convert a binary number to decimal.I 1.J.6.1 Decimal to Binary / Binary to Decimal To convert a decimal number to binary. we multiply the binary digit to "2 raised to the position of the binary number". For Example: 12610 = ? 2 126 63 31 15 7 3 1 / / / / / / / 2 2 2 2 2 2 2 = = = = = = = Quotient 63 31 15 7 3 1 Remainder 0 1 1 1 1 1 1 So.6.5.
you replace it with 8(for octal) or 16 (for hexadecimal). To do that. we will just replace the base number 2 with 8 for Octal and 16 for hexadecimal. writing the remainders from the bottom up. we get the hexadecimal number 7E16 *** Converting octal or hexadecimal numbers is also the same as converting binary numbers to decimal.6.2 Decimal to Octal (or Hexadecimal)/Octal (or Hexadecimal) to Decimal Converting decimal numbers to Octal or hexadecimal is basically the same as converting decimal to binary.E. However. writing the remainders from the bottom up. we get the octal number 1768 For Example (Hexadecimal): 12610 = ? 16 Quotient 126 / 16 = 7 / 16 = 7 Remainder 14 (equal to hex digit E) 7 Write it this way So.J. For Example (Octal): 12610 = ? 8 Quotient 126 / 8 = 15 / 8 = 1/8= 15 1 Remainder 6 7 1 Write it this way So.5.D. instead of having 2 as the divisor.I 1. For Example (Octal): 1768 = ? 10 Position Octal Digits 2 1 1 7 0 6 6 x 80 = 6 7 x 81 = 56 1 x 82 = 64 TOTAL: 126 Introduction to Programming I 22 .
D.J. We then convert each partition into its corresponding octal digit.3 Binary to Octal / Octal to Binary To convert from binary numbers to octal. we partition the binary number into groups of 3 digits (from right to left). and pad it with zeros if the number of digits is not divisible by 3.5. Octal Digit 0 1 2 3 4 5 6 7 Binary Representation 000 001 010 011 100 101 110 111 Table 5: Octal Digits and their corresponding binary represenation For Example: 11111102 = ? 8 0 0 1 1 1 1 7 1 1 1 6 0 Equivalent octal number Converting octal numbers to binary is just the opposite of what is given above. Simply convert each octal digit into its binary representation (given the table) and concatenate them.E.I For Example (Hexadecimal): 7E16 = ? 10 Position Hex Digits 1 7 0 E 14 x 160 = 14 7 x 161 = 112 TOTAL: 126 1.6. The following is a table showing the binary representation of each octal digit. Introduction to Programming I 23 . The result is the binary representation.
The result is the binary representation. Hexadecimal Digit 0 1 2 3 4 5 6 7 8 9 A B C D E F Binary Representation 0000 0001 0010 0011 0100 0101 0110 0111 1000 1001 1010 1011 1100 1101 1110 1111 Table 6: Hexadecimal Digits and their corresponding binary represenation For Example: 11111102 = ? 16 0 1 7 1 1 1 1 E 1 0 Equivalent Hexadecimal number Converting hexadecimal numbers to binary is just the opposite of what is given above.6.J. we partition the binary number into groups of 4 digits (from right to left). We then convert each partition into its corresponding hexadecimal digit.E.4 Binary to Hexadecimal / Hexadecimal to Binary To convert from binary numbers to hexadecimal. Simply convert each hexadecimal digit into its binary representation (given the table) and concatenate them.D.5. and pad it with zeros if the number of digits is not divisible by 4. The following is a table showing the binary representation of each hexadecimal digit. Introduction to Programming I 24 .I 1.
E. Logging into your laboratory's computer 3. 768 to binary.J. Getting the average of three numbers 1. 43F16 to binary.7.2 Number Conversions Convert the following numbers: 1. hexadecimal and octal 2. 10010011012 to decimal. 198010 to binary. You may write your algorithms using pseudocodes or you can use flowcharts. 1.1 Writing Algorithms Given the following set of tasks.I 1.7 Exercises 1. Baking Bread 2. hexadecimal and octal 3. hexadecimal and decimal 4.7. decimal and octal Introduction to Programming I 25 . create an algorithm to accomplish the following tasks.D.
and so on.2 A development environment As a development environment. its name was changed to Java because there was already a language called Oak. One of the first projects developed using Java was a personal hand-held remote control named Star 7. we will be discussing a little bit of Java history and what is Java Technology.1 A programming language As a programming language.3 An application environment Java technology applications are typically general-purpose programs that run on any machine where the Java runtime environment (JRE) is installed. garbage collection and code security Describe the different phases of a Java program 2. al. of Sun Microsystems. the student should be able to: • • Describe the features of Java technology such as the Java virtual machine. Introduction to Programming I 26 . Initially called Oak.2. Java technology provides you with a large suite of tools: a compiler. At about the same time.1 A little Bit of History Java was created in 1991 by James Gosling et al. in honor of the tree outside Gosling's window.E.2.2.D. the World Wide Web and the Internet were gaining popularity. The original motivation for Java was the need for platform independent language that could be embedded in various consumer electronic products like toasters and refrigerators. a class file packaging tool. 2.2 Java Background 2.2 What is Java Technology? 2. Java can create all kinds of applications that you could create using any conventional programming language. 2.2. a documentation generator. 2. realized that Java could be used for Internet programming.2.J.2. We will also discuss the phases that a Java program undergoes.I 2 Introduction to Java 2. Gosling et. an interpreter. At the end of the lesson.2.2.1 Objectives In this section.
which includes basic language classes.D. 2. Most commercial browsers supply a Java technology interpreter and runtime environment.2. The JVM provides the hardware platform specifications to which you compile all Java technology code. This specification enables the Java software to be platform-independent because the compilation is done for a generic machine known as the JVM.3 Some Features of Java 2.3. In Java. after using that allocated memory. In C.2.2. Introduction to Programming I 27 . 2.2.4 A deployment environment There are two main deployment environments: First. A bytecode is a special machine language that can be understood by the Java Virtual Machine (JVM). no matter what type of computer the program was compiled on.3. C++ and other languages the programmer is responsible for this.1 The Java Virtual Machine The Java Virtual Machine is an imaginary machine that is implemented by emulating software on a real machine. This happens automatically during the lifetime of the Java program. However. GUI component classes. This can be difficult at times since there can be instances wherein the programmers forget to deallocate memory and therefor result to what we call memory leaks.2 Garbage Collection Many programming languages allows a programmer to allocate memory during runtime.I 2.2. there should be a way to deallocate that memory block in order for other programs to use it again. the programmer is freed from the burden of having to deallocate that memory themselves by having what we call the garbage collection thread. The garbage collection thread is responsible for freeing any memory that can be freed. The bytecode is independent of any particular computer hardware.J.E. and so on. The other main deployment environment is on your web browser. the JRE supplied by the Java 2 Software Development Kit (SDK) contains the complete set of class files for all the Java technology packages. so any computer with a Java interpreter can execute the compiled Java program.
E. the memory layout of the executable is then determined. After loading all the classes. This limits any Trojan horse applications since local classes are always loaded first. The Class Loader is responsible for loading all classes needed for the Java program.3 Code Security Code security is attained in Java through the implementation of its Java Runtime Environment (JRE). It adds security by separating the namespaces for the classes of the local file system from those that are imported from network sources. code verification (through the bytecode verifier) and finally code execution. the bytecode verifier then tests the format of the code fragments and checks the code fragments for illegal code that can violate access rights to objects.D. The JRE runs code compiled for a JVM and performs class loading (through the class loader).I 2. After all of these have been done.J. This adds protection against unauthorized access to restricted areas of the code since the memory layout is determined during runtime.3. the code is then finally executed. Introduction to Programming I 28 .2. After loading the class and layouting of memory.
java.class file is then interpreted by the Java interpreter that converts the bytecodes into the machine language of the particular computer you are using. Figure 2. After creating and saving your Java program. The . compile the program by using the Java Compiler. vi.I 2.E.4 Phases of a Java Program The following figure describes the process of compiling and executing a Java program. class. emacs. etc.java extension File with .J. The output of this process is a file of Java bytecodes with the file extension . Examples of text editors you can use are notepad. Task Write the program Compile the program Run the program Tool to use Any text editor Java Compiler Java Interpreter Output File with . This file is stored in a disk file with the extension .D.class extension (Java bytecodes) Program Output Table 7: Summary of Phases of a Java Program Introduction to Programming I 29 .1: Phases of a Java Program The first step in creating a Java program is by writing your programs in a text editor.2.
the first one is by using a console and a text editor. a compiler and/or interpreter and a debugger. At the end of the lesson. For the Windows XP version of this section.E. please refer to Appendix A. } } Before we try to explain what the program means. For instructions on how to install Java and Netbeans.out. There are two ways of doing this.println("Hello world!").J. you have installed Java and Netbeans in your system. This tutorial uses RedHat Linux as the operating system. 3.I 3 Getting to know your Programming Environment 3. The second one is by using Netbeans which is an Integrated Development Environment or IDE. compile and run Java programs. let us first take a look at the first Java program you will be writing. Introduction to Programming I 30 . please refer to Appendix B.2 Introduction An IDE is a programming environment integrated into a software application that provides a GUI builder. a text or code editor.3 My First Java Program public class Hello { /** * My first java program */ public static void main(String[] args) { //prints the string "Hello world" on screen System. the student should be able to: • • • Create a Java program using text editor and console in the Linux environment Differentiate between syntax-errors and runtime errors Create a Java program using Netbeans 3.1 Objectives In this section. Make sure that before you do this tutorial. we will be discussing on how to write. let's first try to write this program in a file and try to run it.D. Before going into details.
You will also need to open the Terminal window to compile and execute your Java programs.I 3.4 Using a Text Editor and Console For this example. click on Menu-> Accessories-> Text Editor.1: Opening the Text Editor Introduction to Programming I 31 . Step 1: Start the Text Editor To start the Text Editor in Linux.2: Text Editor Application in Linux Figure 3.J.D. we will be using a text editor to edit the Java source code.E. Figure 3.
Figure 3. click on Menu-> System Tools-> Terminal.D.I Step 2: Open Terminal To open Terminal in Linux.4: Terminal in Linux Figure 3.3: Opening the Terminal Introduction to Programming I 32 .E.J.
E.D.5: Writing the Source Code with the Text Editor Introduction to Programming I 33 .J.I Step 3: Write your the source code of your Java program in the Text Editor Figure 3.
J. Figure 3. click on the File menu found on the menubar and then click on Save.java".E.D. and we will be saving it inside a folder named MYJAVAPROGRAMS.I Step 4: Save your Java Program We will save our program on a file named "Hello. To open the Save dialog box.6: Saving the Source Code Introduction to Programming I 34 .
E.J.D. a dialog box will appear as shown in Figure below.I After doing the procedure described above. Figure 3.7: Save As Dialog Introduction to Programming I 35 .
E.I Now. Type on the "Folder Name" Textbox MYJAVAPROGRAMS. Click on the button encircled in the figure below to create the folder.D. and click on the CREATE button. A dialog box named "New Folder" will then appear.J. We shall name this folder MYJAVAPROGRAMS. Figure 3.8: Creating New Folder Introduction to Programming I 36 . we'll create a new folder inside the root folder where we will save your programs.
J. Figure 3.E.D.I Now that we've created the folder where we will save all the files.9: Opening the Created Folder Introduction to Programming I 37 . double click on that folder to open it.
The folder should be empty for now since it's a newly created folder and we haven't saved anything in it yet.10: View Inside The Created Folder Introduction to Programming I 38 .E.D.I You will see a similar figure as shown below after you clicked on MYJAVAPROGRAMS.J. Figure 3.
in the Selection textbox. and then click on the OK button.11: Saving the Source Code Inside the Created Folder Introduction to Programming I 39 .I Now. which is "Hello. Figure 3.J.java".D. type in the filename of your program.E.
you can just edit it.D. Figure 3. notice how the title of the frame changes from "Untitled 1 (modified) – gedit" to "/root/MYJAVAPROGRAMS/Hello.E.java . Take note that if you want to make changes in your file. and then save it again by clicking on File -> Save.J.gedit".12: New Window After Saving Introduction to Programming I 40 .I Now that you've saved your file.
you can see here that there is a folder named "MYJAVAPROGRAMS" which we have created a while ago. when you open the terminal window. Now let's go inside that directory.E. type ls and then press ENTER. the next step is to compile your program.I Step 5: Compiling your program Now. What you will see is a list of files and folders inside your home folder. To see what is inside that home folder. it opens up and takes you directly to what is called your home folder. Go to the Terminal window we just opened a while ago.java program.13: Lists of Files in the Home Folder Now.D. Figure 3. Typically.J. and where we saved our Hello. Introduction to Programming I 41 .
you type in: cd MYJAVAPROGRAMS Figure 3. you type in the command: cd [directory name].E. The "cd" command stands for.14: Changing the Directory Introduction to Programming I 42 . since the name of our directory is MYJAVAPROGRAMS. change directory.J.I To go inside a directory.D. In this case.
let us now start compiling your Java program.15: List of Files Inside the New Directory Introduction to Programming I 43 . In order to do that.I Once inside the folder where your Java programs are.E. you should make sure that the file is inside the folder where you are in. execute the "ls" command again to see if your file is inside that folder. Figure 3.D.J. Take note that.
javac adds a file to the disk called [filename]. Introduction to Programming I 44 .J.class.16: Compiling Java File During compilation. Figure 3.I To compile a Java program. So in this case. we type in the command: javac [filename].class.E. or in this case. type in: javac Hello.java. Hello. which is the actual bytecode.D.
"Hello world!". To run your Java program.J.17: Running Class File Introduction to Programming I 45 .E. type in: java Hello You can see on the screen that you have just run your first Java program that prints the message. we are now ready to run your program.I Step 6: Running the Program Now. type in the command: java [filename without the extension].D. Figure 3. so in the case of our example. assuming that there are no problems during compilation (we'll explore more of the problems encountered during compilation in the next section).
and omission of correct punctuation. the problem may not be at the exact point. the use of incorrect special characters. our Hello.18: Source Code With Errors Introduction to Programming I 46 . Other common mistakes are in capitalization. Figure 3. 3.4. As discussed before. Let's take for example.1 Errors What we've shown so far is a Java program wherein we didn't encounter any problems in compiling and running. there are two types of errors.java program wherein we intentionally omit the semicolon at one statement and we try to type the incorrect spelling of a command. The second one is the runtime error. we usually encounter errors along the way.J.D. You may have misspelled a command in Java or forgot to write a semi-colon at the end of a statement. However. Java attempts to isolate the error by displaying the line of code and pointing to the first incorrect character in that line.E. spelling. The first one is a compile-time error or also called as syntax error.1.4.I 3. However. As what we have discussed in the first part of this course.1 Syntax Errors Syntax errors are usually typing errors. this is not always the case.
Doing so may reduce the total number of errors dramatically. The second error message suggests that there is a missing semicolon after your statement. The first error message suggests that there is an error in line 6 of your program. It pointed to the next word after the statict. Even programs that compile successfully may display wrong answers if the programmer has not thought through the logical processes and structures of the program.I See the error messages generated after compiling the program. and try to compile the program again.4. try to correct the first mistake in a long list.J. which should be spelled as static. Figure 3.E.1. if you encounter a lot of error messages.D. 3.19: Compiling the Source Code with Errors As a rule of thumb. Introduction to Programming I 47 .2 Run-time Errors Run-time errors are errors that will not display until you run or execute your program.
In this part of the lesson.20: Running Netbeans with the Command-Line Introduction to Programming I 48 . a compiler and/or interpreter and a debugger. we will be using Netbeans. To run Netbeans using command-line.D.5 Using Netbeans Now that we've tried doing our programs the complicated way.J. One is through command-line using terminal. Step 1: Run Netbeans There are two ways to run Netbeans. let's now see how to do all the processes we've described in the previous sections by using just one application. which is an Integrated Development Environment or IDE.E.I 3. An IDE is a programming environment integrated into a software application that provides a GUI builder. a text or code editor. Open terminal (see steps on how to run terminal in the previous discussion). or by jst clicking on the shortcut button found on the main menu. and type: netbeans Figure 3.
Figure 3.I The second way to run Netbeans.E.D.21: Running Netbeans using the Menu Introduction to Programming I 49 . is by clicking on Menu-> Programming-> More Programming Tools-> Netbeans.J.
Figure 3.22: Window After Openning Netbeans Introduction to Programming I 50 .J.E.D.I After you've open NetBeans IDE. you will see a graphical user interface (GUI) similar to what is shown below.
Figure 3.23: Starting New Project Introduction to Programming I 51 .I Step 2: Make a project Now.D. let's first make a project.E. Click on File-> New Project.J.
I After doing this.E.D.J. a New Project dialog will appear. Figure 3.24: Choosing Project Type Introduction to Programming I 52 .
J.E.D.25: Choosing Java Application as Project Type Introduction to Programming I 53 .I Now click on Java Application and click on the NEXT button. Figure 3.
E. Edit the Project Name part and type in "HelloApplication". Figure 3.I Now.D.J.26: Setting the Project Name Introduction to Programming I 54 . a New Application dialog will appear.
E.27: Setting the Project Location Introduction to Programming I 55 .I Now try to change the Application Location. Figure 3. by clicking on the BROWSE button.J.D.
J.D. Figure 3.E.28: Opening the Root Folder Introduction to Programming I 56 .I A Select Project Location dialog will then appear. Double-click on the root folder.
E.D.I The contents of the root folder is then displayed.J.29: Choosing the Folder MYJAVAPROGRAMS as Project Location Introduction to Programming I 57 . Now double-click on the Figure 3. MYJAVAPROGRAMS folder and click on the OPEN button.
I See now that the Project root/MYJAVAPROGRAMS.30: Window after Setting the Project Location to MYJAVAPROGRAMS Introduction to Programming I 58 .D. Location and Project Folder is changed to / Figure 3.E.J.
and then click on the FINISH button. on the Create Main Class textfield. Figure 3.D.E.I Finally. type in Hello as the main class' name.31: Setting the Main Class of the Project to Hello Introduction to Programming I 59 .J.
E.D. Figure 3. NetBeans automatically creates the basic code for your Java program.32: View of the Created Project Introduction to Programming I 60 . where you set the Project location. On the left side of the window. let us first describe the main window after creating the project.I Step 3: Type in your program Before typing in your program. As shown below. This can all be found in your MYJAVAPROGRAMS folder. you can see a list of folders and files that NetBeans generated after creating the project.J. You can just add your own statements to the generated code.
after the statement. try to modify the code generated by Netbeans. Ignore the other parts of the program for now.J.E. as we will explain the details of the code later.println("Hello world!").D.33: Inserting the Code Introduction to Programming I 61 . Insert the code: System. Figure 3. //TODO code application logic here.out.I Now.
I Step 4: Compile your program Now. just click on Build -> Build Main Project.J.D. Figure 3. to compile your program.35: Compiling with Netbeans Using the Shortcut Button Introduction to Programming I 62 . Figure 3. you could also use the shortcut button to compile your code.34: Compiling with Netbeans Using the Build Menu Or.E.
I If there are no errors in your program. Figure 3. you will see a build successful message on the output window.E.36: View after a Successful Compilation Introduction to Programming I 63 .D.J.
Figure 3.E. click on Run-> Run Main Project.I Step 5: Run your program To run your program.J.37: Running with Netbeans using the Run Menu Or you could also use the shortcut button to run your program.D. Figure 3.38: Running with Netbeans using the Shortcut Button Introduction to Programming I 64 .
Figure 3.D.E.J.I The output of your program is displayed in the output window.39: View after a Successful Run Introduction to Programming I 65 .
The program should output on the screen: Welcome to Java Programming [YourName]!!! 3. Introduction to Programming I 66 . The program should output the following lines on the screen: I think that I shall never see.2 The Tree Using Netbeans.J. A tree whose hungry mouth is pressed Against the Earth’s sweet flowing breast.E.6 Exercises 3. create a class named: TheTree. create a class named: [YourName].1 Hello World! Using Netbeans. a poem as lovely as a tree.6.D.I 3.6.
which indicates that our class in accessible to other classes from other packages (packages are a collection of classes). public class Hello indicates the name of the class which is Hello.I 4 Programming Fundamentals 4. however.identifiers and operators Develop a simple valid Java program using the concepts learned in this chapter 4. At the end of the lesson. We will also be discussing some coding guidelines or code conventions along the way to help in effectively writing readable programs.J. we'll try to the dissect your first Java program: public class Hello { /** * My first java program */ public static void main(String[] args) { //prints the string "Hello world" on screen System. we can also place this next to the first line of our code. We will be covering packages and access specifiers later.D.2 Dissecting my first Java program Now.java program introduced in the previous section. We do this by using the class keyword. primitive data types.1 Objectives In this section. the student should be able to: • • • Identify the basic parts of a Java program Differentiate among Java literals.println("Hello world!"). variable types .E. all code should be placed inside a class declaration. We will start by trying to explain the basic parts of the Hello. So. we will be discussing the basic parts of a Java program. we placed the curly brace at the next line after the class declaration. the class uses an access specifier public. In Java. The next line which contains a curly brace { indicates the start of a block. In addition. } } The first line of the code. In this code. we could actually write our code as: public class Hello { public class Hello { or Introduction to Programming I 67 .out.
It is good programming practice to add comments to your code. if the name of your public class is Hello.java extension.J. but used for documentation purposes.println("Hello world!"). It is not part of the program itself. The main method is the starting point of a Java program. //prints the string "Hello world" on screen Now. public static void main(String[] args) { indicates the name of one method in Hello which is the main method. prints the text enclosed by quotation on the screen. Your Java programs should always end with the . So for example. The next line. we learned two ways of creating comments. Make sure to follow the exact signature. You should write comments in your code explaining what a certain class does. 3. The next line. 2.D. A comment is something used to document a part of a code. and the other one is by writing // at the start of the comment. All programs except Applets written in Java start with the main method. The last two lines which contains the two curly braces is used to close the main method and class respectively. System. Coding Guidelines: 1.java. The command System.println(). The next line is also a Java comment.I The next three lines indicates a Java comment. you should save it in a file called Hello. Introduction to Programming I 68 . Anything within these delimiters are ignored by the Java compiler. public static void main(String[] args) { or can also be written as.out. Filenames should match the name of your public class. /** * My first java program */ A comment is indicated by the delimiters “/*” and “*/”.E.out. or what a certain method do. and are treated as comments. prints the text “Hello World!” on screen. The first one is by placing the comment inside /* and */.
Those text are not part of the program and does not affect the flow of the program. For example. It uses tags like: @author Florence Balagtas @version 1. /* this is an exmaple of a C style or multiline comments */ 4. /** This is an example of special java doc comments used for \n generating an html documentation. Like C-style comments. Unlike C++ style comments. For example. C-style multiline comments and special javadoc comments.I 4. For example.3. All the text after // are treated as comments. Java supports three types of comments: C++-style single line comments.3 Java Comments Comments are notes written to a code for documentation purposes.2 C-Style Comments C-style comments or also called multiline comments starts with a /* and ends with a */. It can also contain certain tags to add more information to your comments. You can create javadoc comments by starting the line with /** and ending it with */. All text in between the two delimeters are treated as comments.2 */ Introduction to Programming I 69 .E.3. it can span multiple lines. it can also span lines.D. // This is a C++ style or single line comments 4.J. 4.1 C++-Style Comments C++ Style comments starts with //.3.3 Special Javadoc Comments Special Javadoc comments are used for generating an HTML documentation for your Java programs.
J.println("world").4 Java Statements and blocks A statement is one or more lines of code terminated by a semicolon. An example of a single statement is. you can place the opening curly brace in line with the statement. An example of a block is.out.E.D. System. System.out.I 4. public static void main( String[] args ){ System. public static void main( String[] args ){ System. like for example.for example. System. Any amount of white space is allowed. } Coding Guidelines: 1.out. like.println(“Hello world”). You should indent the next statements after the start of a block.out.println("Hello").println("world"). A block is one or more statements bounded by an opening and closing curly braces that groups the statements as one unit. public static void main( String[] args ){ or you can place the curly brace on the next line.println("Hello").out. public static void main( String[] args ) { 2. } Introduction to Programming I 70 . Block statements can be nested indefinitely. In creating blocks.
use capital letters to indicate the start of the word except the first word.I 4. This means that the identifier: Hello is not the same as hello.J.D. Letters may be lower or upper case. System. 3. Java identifiers are case-sensitive. out.5 Java Identifiers Identifiers are tokens that represent names of variables. For names of methods and variables. Identifiers must begin with either a letter. capitalize the first letter of the class name. void. main. Examples of identifiers are: Hello. For example. or a dollar sign “$”. charArray. fileNumber. the first letter of the word should start with a small letter. Introduction to Programming I 71 . etc. We will discuss more about Java keywords later. Subsequent characters may use numbers 0 to 9. Avoid using underscores at the start of the identifier such as _read or _write.E. Coding Guidelines: 1. etc. In case of multi-word identifiers. methods. public.For example: ThisIsAnExampleOfClassName thisIsAnExampleOfMethodName 2. Identifiers cannot use Java keywords like class. classes. ClassName. For names of classes. an underscore “_”.
D.6 Java Keywords Keywords are predefined identifiers reserved by Java for a specific purpose. Here is a list of the Java Keywords. Introduction to Programming I 72 .1: Java Key Words We will try to discuss all the meanings of these keywords and how they are used in our Java programs as we go along the way.J.E. methods …etc. Figure 4.I 4. classes. You cannot use keywords as names for your variables.
8345e2 is in scientific notation.D. and octal (base 8). while in hexadecimal. Character Literals and String Literals. It's decimal representation is 12. Introduction to Programming I 73 . For decimal numbers. consider the number 12. and in octal. Integer literals default to the data type int. you may wish to force integer literal to the data type long by appending the “l” or “L” character. Boolean Literals. For example. while 5.3 Boolean Literals Boolean literals have only two values.7. we have to follow some special notations.7. Floating-Point Literals. For hexadecimal numbers.2 Floating-Point Literals Floating point literals represent decimals with fractional parts. 4. 4. To use a smaller precision (32-bit) float.1415. they are preceeded by “0”.7.J. just append the “f” or “F” character. The different types of literals in Java are: Integer Literals. it is 0xC. For example. An int is a signed 32-bit value. 583.E. For octals. Floating point literals default to the data type double which is a 64-bit value. We will cover more on data types later. it should be preceeded by “0x” or “0X”.1 Integer Literals Integer literals come in different formats: decimal (base 10). An example is 3. In using integer literals in our program. it is equivalent to 014.7 Java Literals Literals are tokens that do not change or are constant. Floating point literals can be expressed in standard or scientific notations. A long is a signed 64-bit value.45 is in standard notation. hexadecimal (base 16). We just write a decimal number as it is. 4.I 4. In some cases. true or false. we have no special notations.
5 String Literals String literals represent multiple characters and are enclosed by double quotes. ‘\b’ for backspace.J. ‘\n’ for the newline character. ‘\r’ for the carriage return. For example. “Hello World”. the letter a.7. To use a character literal. is represented as ‘a’. 4.D. a backslash is used followed by the character code. Introduction to Programming I 74 .I 4.E. An example of a string literal is. For example. To use special characters such as a newline character. A Unicode character is a 16-bit character set that replaces the 8-bit ASCII character set. enclose the character in single quote delimiters.7.4 Character Literals Character Literals represent single Unicode characters. Unicode allows the inclusion of symbols and special characters from other languages.
It has it’s literal enclosed in double quotes(“”).8. char (for textual). boolean (for logical). It must have its literal enclosed in single quotes(’ ’).J. For example. It is not a primitive data type. 4. double and float (floating point). long (integral).2 Textual – char A character data type (char). boolean result = true. '\'' '\"' //for single quotes //for double quotes Although. The example shown above. represents a single Unicode character. For example. int. String message=“Hello world!” Introduction to Programming I 75 . An example is. declares a variable named result as boolean type and assigns it a value of true.1 Logical .8 Primitive data types The Java programming language defines eight primitive data types. String is not a primitive data type (it is a Class). For example. byte.boolean A boolean data type represents two states: true and false. use the escape character \. ‘a’ ‘\t’ //The letter a //A tab To represent special characters like ' (single quotes) or " (double quotes).8. it is a class.E. 4. The following are. A String represents a data type that contains multiple characters. we will just introduce String in this section. short.D.I 4.
3 Integral – byte.8.J. short.E. a lowercase L is not recommended because it is hard to distinguish from the digit 1.I 4. Introduction to Programming I 76 . You can define its long value by appending the letter l or L. 2 //The 077 //The 0xBACC uses three forms – decimal. Integral data type have the following ranges: Integer Length 8 bits 16 bits 32 bits 64 bits Name or Type byte short int long -27 -215 -231 -263 Range to to to to 27-1 215-1 231-1 263-1 Table 8: Integral types and their ranges Coding Guidelines: In defining a long value.D. octal or hexadecimal. Examples decimal value 2 leading 0 indicates an octal value //The leading 0x indicates a hexadecimal value Integral types has int as default data type. int & long Integral data types in Java are.
02E23 //A large floating-point value 2.J.14 //A simple floating-point value (a double) 6. Floating-point data types have the following ranges: Float Length 32 bits 64 bits Name or Type float double -231 -263 Range to to 231-1 263-1 Table 9: Floating point types and their ranges Introduction to Programming I 77 .E. Floating-point literal includes either a decimal point or one of the following.8. 3.4E+306D //A large double value with redundant D In the example shown above.D.718F //A simple float size value 123.02E+23. That example is equivalent to 6. E or e //(add exponential value) F or f //(float) D or d //(double) Examples are.I 4. the 23 after the E in the second example is implicitly positive.4 Floating Point – float and double Floating point types has double as default data type.
Here is a sample program that declares and initializes some variables. is preferred over the declaration. Declare one variable per line of code. double grade = 0. Use descriptive names for your variables. It always good to initialize your variables as you declare them.9.9 Variables A variable is an item of data used to store state of objects. option = 'C'. public class VariableSamples { public static void main( String[] args ){ //declare a data type with variable name // result and boolean data type boolean result. name it as.1 Declaring and Initializing Variables To declare a variable is as follows. A variable has a data type and a name. } } Coding Guidelines: 1. double quiz=10. Note: Values enclosed in <> are required values.D. double exam=0. grade=0. double data type and initialized //to 0. The data type indicates the type of value that the variable can hold. while those values enclosed in [] are optional. Introduction to Programming I 78 .0. For example. The variable name must follow rules for identifiers. if you want to have a variable that contains a grade for a student. quiz=10. Like for example. double exam=0.I 4.E.J. grade and not just some random letters you choose. <data type> <name> [=initial value]. 4. //assign 'C' to option //declare a data type with variable name //grade. 3.0 double grade = 0. 2. the variable declarations. //declare a data type with variable name // option and char data type char option.
} } The program will output the following text on screen.out. System.println("world!"). Consider the statements.println( “The value of x=“ + x ).out. System.out. System.D.print ()? The first one appends a newline at the end of the data to output. Hello world! Introduction to Programming I 79 . char x. System.out.println( value ). public class OutputVariable { public static void main( String[] args ){ int value = 10. These statements will output the following on the screen.9.println() and System.3 System.out.I 4. x = ‘A’. 10 The value of x=A 4.print("Hello ").9.print("world!"). System.print() What is the difference between the commands System.out. System. System. System.2 Outputting Variable Data In order to output the value of a certain variable. These statements will output the following on the screen. we can use the following commands.println("Hello "). while the latter doesn't.out.println() vs.out.out.out.println() System.out.print() Here's a sample program.E.out. Hello world! Now consider the following statements.J.
It points to another memory location of where the actual data is.4 Reference Variables vs. For the reference variable name. Introduction to Programming I 80 . When you declare a variable of a certain class. you are actually declaring a reference variable to the object with that certain class. They store data in the actual memory location of where the variable is.J.E. Primitive variables are variables with primitive data types. the variable name and the data they hold. wherein you have the address of the memory cells. Reference variables are variables that stores the address in the memory location. int num = 10.9. for the primitive variable num. These are reference variables and primitive variables.D. For example. the variable just holds the address of where the actual data is. String name = "Hello" Suppose. the illustration shown below is the actual memory of your computer. the data is on the actual location of where the variable is.I 4. Memory Address 1001 : 1563 : : 2000 name Variable Name num Data 10 : Address(2000) : : "Hello" As you can see. suppose we have two variables with data types int and String. Primitive Variables We will now differentiate the two types of variables that Java programs have.
relational operators.J.10 Operators In Java. logical operators and conditional operators.E.D.op2 Description Adds op1 and op2 Multiplies op1 by op2 Divides op1 by op2 Computes the remainder of dividing op1 by op2 Subtracts op2 from op1 Table 10: Arithmetic operations and their functions Introduction to Programming I 81 .1 Arithmetic operators Here are the basic arithmetic operators that can be used in creating your Java programs.I 4. There are arithmetic operators. Operator + * / % Use op1 + op2 op1 * op2 op1 / op2 op1 % op2 op1 . These operators follow a certain kind of precedence so that the compiler will know which operator to evaluate first in case multiple operators are used in one statement.10. 4. there are different types of operators.
out.out.println("Variable values.out. System. //multiplying numbers System.y = " + (x . System.println(" x + y = " + (x + y)).").out..out.").println("Mixing types.out.y)). //subtracting numbers System. int j = 42. / j)). double x = 27. System.. double y = 7.D.out. System.j)).. } } Introduction to Programming I 82 .").out.out.out.j = " + (i .println("Dividing. System.println("Subtracting.println(" i * x = " + (i * x)). //adding numbers System.println(" x = " + x).println(" x / y = " + (x numbers * j))..out.out. System. System. System. //mixing types System.. System.println(" y = " + y).println(" i / j = " + (i System.22.out.").").println(" i * j = " + (i System..E.println(" i = " + i).out..out.println(" x * y = " + (x //dividing numbers System..out.out. System. System...J.println("Adding.println(" i % j = " + (i % j)).println(" i + j = " + (i + j)).I Here's a sample program in the usage of these operators: public class ArithmeticDemo { public static void main(String[] args) { //a few numbers int i = 37.").out.println(" j + y = " + (j + y)).out.475. System. System. System. //computing the remainder resulting from dividing System. System.out.println(" j = " + j).println(" x .println(" i .out.. / y)).println("Multiplying.println(" x % y = " + (x % y)).out. * y))..out.").println("Computing the remainder...
. i / j = 0 x / y = 3. i * j = 1554 x * y = 198..22 Adding.y = 20. i % j = 37 x % y = 5.8054 Computing the remainder.475 y = 7. i = 37 j = 42 x = 27..j = -5 x ..D.. i . j + y = 49..37 Dividing. The integer is implicitly converted to a floating-point number before the operation takes place.695 Subtracting.I Here is the output of the program.E.815 Mixing types. the result is a floating point.58 Note: When an integer and a floating-point number are used as operands to a single arithmetic operation.J...22 i * x = 1016..255 Multiplying. Introduction to Programming I 83 .. i + j = 79 x + y = 34.... Variable values..
evaluates to the value of op before it was decremented Decrements op by 1. Operator ++ ++ Use op++ ++op Description Increments op by 1. evaluates to the value of op after it was incremented Decrements op by 1. int j = 3.D. evaluates to the value of op before it was incremented Increments op by 1. the expression. When used before an operand. Java also includes a unary increment operator (++) and unary decrement operator (--). count = count + 1.I 4. is equivalent to.J. int k = 0. int i = 10. Increment and decrement operators increase and decrease a value stored in a number variable by 1. //will result to k = 4+10 = 14 Introduction to Programming I 84 . it causes the variable to be incremented or decremented by 1.E. For example.10. k = ++j + i. count++. evaluates to the value of op after it was decremented //increment the value of count by 1 -- op-- -- --op Table 11: Increment and Decrement operators The increment and decrement operators can be placed before or after an operand. and then the new value is used in the expression in which it appears.2 Increment and Decrement operators Aside from the basic arithmetic operators. For example.
J.E.I When the increment and decrement operators are placed after the operand. int i = 10. For example. int j = 3. the old value of the variable will be used in the expression where it appears. //will result to k = 3+10 = 13 Coding Guideline: Always keep expressions containing increment and decrement operators simple and easy to understand. Introduction to Programming I 85 . k = j++ + i.D. int k = 0.
The output of evaluation are the boolean values true or false. Operator > >= < <= == != Use op1 > op2 op1 >= op2 op1 < op2 op1 <= op2 op1 == op2 op1 != op2 Description op1 is greater than op2 op1 is greater than or equal to op2 op1 is less than op2 op1 is less than or equal to op2 op1 and op2 are equal op1 and op2 are not equal Table 12: Relational Operators Introduction to Programming I 86 .D.3 Relational operators Relational operators compare two values and determines the relationship between those values.10.J.I 4.E.
out.println(" k != j = " + (k != j)).println(" i == j = " + (i == j)). //false //less than or equal to System.out.J.println(" i >= j = System.out. //greater than System.out.println(" k <= j = " + (k <= j))... //true //not equal to System.out.. //true " + (k >= j)). System. //true //greater than or equal to System. //false System.out.out.. int j = 42.println(" k == j = " + (k == j)). " + (i >= j)). //true System.out.. j = " + (i > j)).out.out.I Here's a sample program that uses relational operators.println(" k >= j = //less than System..println(" i != j = " + (i != j)).").println(" j < i = " + (j < i)). System..println("Greater System.out.println(" k < j = " + (k < j)). //true System.out..out.out.").").println(" i <= j = " + (i <= j)). //true j = " + (k > j)). //false or equal to..out.println("Not equal to.println("Less than or equal to.out. System. //false System. public class RelationalDemo { public static void main(String[] args) { //a few numbers int i = 37. //false } } Introduction to Programming I 87 .println(" j > System.out."). System.. //false System.out. //false " + (j >= i))..println("Variable values.println(" j <= i = " + (j <= i)). System.println("Greater than System.out. //false i = " + (j > i)). int k = 42.out.out.. System.println("Less than.println("Equal to.").println(" k = " + k).println(" i = " + i).")..out.println(" k > than.out.E.println(" i > System.out."). //true System.println(" j >= i = System. //true //equal to System.out.D. System.out.println(" j = " + j).println(" i < j = " + (i < j)). System..
.... i < j = true j < i = false k < j = false Less than or equal to. i >= j = false j >= i = true k >= j = true Less than..I Here's the output from this program: Variable values. i = 37 j = 42 k = 42 Greater than. i != j = true k != j = false Introduction to Programming I 88 . i == j = false k == j = true Not equal to.J..D...... i > j = false j > i = true k > j = false Greater than or equal to.E. i <= j = true j <= i = false k <= j = true Equal to....
^ (boolean logical exclusive OR). variables or constants. Introduction to Programming I 89 . and op is either &&.D. ||.I 4.10.4 Logical operators Logical operators have one or two boolean operands that yield a boolean result. x2 can be boolean expressions. | or ^ operator.E. &.J. The basic expression for a logical operation is. and ! (logical NOT). || (logical OR). summarize the result of each operation for all possible combinations of x1 and x2. | (boolean logical inclusive OR). & (boolean logical AND). x1 op x2 where x1. The truth tables that will be shown next. There are six logical operators: && (logical AND).
the & operator always evaluates both exp1 and exp2 before returning an answer.out. What does this mean? Given an expression. } } Introduction to Programming I 90 .println(i). x1 TRUE TRUE FALSE FALSE x2 TRUE FALSE TRUE FALSE Result TRUE FALSE FALSE FALSE Table 13: Truth table for & and && The basic difference between && and & operators is that && supports short-circuit evaluations (or partial evaluations).D. boolean test= false.E.out. In contrast. exp1 && exp2 && will evaluate the expression exp1. the operator never evaluates exp2 because the result of the operator will be false regardless of the value of exp2. System. Here's a sample source code that uses logical and boolean AND.I 4. System. and immediately return a false value is exp1 is false.4.println(test).println(i). //demonstrate && test = (i > 10) && (j++ > 9). int j = 10.println(j).out. public class TestAND { public static void main( String[] args ){ int i = 0. System.println(test).out.J.out.out.1 && (logical AND) and & (boolean logical AND) Here is the truth table for && and &.println(j). If exp1 is false. System.10. System. while & doesn't. //demonstrate & test = (i > 10) & (j++ > 9). System.
D.J. 0 10 false 0 11 false Note. that the j++ on the line containing the && operator is not evaluated since the first expression (i>10) is already equal to false. Introduction to Programming I 91 .I The output of the program is.E.
public class TestOR { public static void main( String[] args ){ int i = 0. In contrast. exp1 || exp2 || will evaluate the expression exp1.4.out.D. while | doesn't.out.println(i). //demonstrate || test = (i < 10) || (j++ > 9).println(i). } } Introduction to Programming I 92 . System. System.10. What does this mean? Given an expression.out. System.E. //demonstrate | test = (i < 10) | (j++ > 9).out.I 4.J.out.out.println(test). the operator never evaluates exp2 because the result of the operator will be true regardless of the value of exp2. System. and immediately return a true value is exp1 is true. System.println(j). Here's a sample source code that uses logical and boolean OR.2 || (logical OR) and | (boolean logical inclusive OR) Here is the truth table for || and |. the | operator always evaluates both exp1 and exp2 before returning an answer. boolean test= false.println(j). System. x1 TRUE TRUE FALSE FALSE x2 TRUE FALSE TRUE FALSE Result TRUE TRUE TRUE FALSE Table 14: Truth table for | and || The basic difference between || and | operators is that || supports short-circuit evaluations (or partial evaluations). If exp1 is true. int j = 10.println(test).
E. 0 10 true 0 11 true Note.J.I The output of the program is. Introduction to Programming I 93 .D. that the j++ on the line containing the || operator is not evaluated since the first expression (i<10) is already equal to true.
out. Here's a sample source code that uses the logical exclusive OR operator. System.out.println(val1 ^ val2). false true false true Introduction to Programming I 94 .println(val1 ^ val2). System.E.println(val1 ^ val2). val2 = false.3 ^ (boolean logical exclusive OR) Here is the truth table for ^. val1 = false.D.println(val1 ^ val2).I 4. val2 = false. val1 = false.10.out.J. Note that both operands must always be evaluated in order to calculate the result of an exclusive OR. if and only if one operand is true and the other is false. val1 = true. boolean val2 = true. x1 TRUE TRUE FALSE FALSE x2 TRUE FALSE TRUE FALSE Table 15: Truth table for ^ Result FALSE TRUE TRUE FALSE The result of an exclusive OR operation is TRUE.out. public class TestXOR { public static void main( String[] args ){ boolean val1 = true. } } The output of the program is. System. System. val2 = true.4.
Here is the truth table for !.4 ! (logical NOT) The logical NOT takes in one argument.println(!val1). variable or constant.10. } } The output of the program is.I 4.D.E.J. boolean val2 = false. wherein that argument can be an expression. x1 TRUE FALSE Result FALSE TRUE Table 16: Truth table for ! Here's a sample source code that uses the logical NOT operator. System. public class TestNOT { public static void main( String[] args ){ boolean val1 = true.4.out. System. false true Introduction to Programming I 95 .println(!val2).out.
10. Passed Introduction to Programming I 96 . exp2 is the value returned.out. If it is false.5 Conditional Operator (?:) The conditional operator ?: is a ternary operator. If exp1 is true. exp1?exp2:exp3 wherein exp1 is a boolean expression whose result must either be true or false. public class ConditionalOperator { public static void main( String[] args ){ String status = "".I 4.D. given the code. This means that it takes in three arguments that together form a conditional expression.E.println( status ). The structure of an expression using a conditional operator is. int grade = 80.J. //print status System. } } The output of this program will be. //get status of the student status = (grade >= 60)?"Passed":"Fail". then exp3 is returned. For example.
out.J.D. answer = 'a'.I Here is the flowchart of how ?: works.2: Flowchart using the ?: operator Here is another program that uses the ?: operator. } } score = (answer == 'a') ? 10 : 0. The output of the program is. System. Score = 10 Introduction to Programming I 97 .E.println("Score = " + score ). class ConditionalOperator { public static void main( String[] args ){ int char score = 0. Figure 4.
I 4.6 Operator Precedence Operator precedence defines the compiler’s order of evaluation of operators so as to come up with an unambiguous result. Introduction to Programming I 98 . Coding Guidelines To avoid confusion in evaluating mathematical operations. ((6%2)*5)+(4/2)+88-10. 6%2*5+4/2+88-10 we can re-write the expression and place some parenthesis base on operator precedence.J.10.3: Operator Precedence Given a complicated expression.E. Figure 4.D. keep your expressions simple and use parenthesis.
4 Operator precedence Given the following expressions. your program should output. For example. declare the following variables with the corresponding data types and initialization values.I 4.11. given the numbers 10. number 1 = number 2 = number 3 = Average is 10 20 45 = 25 4. Variable name number letter result str Data Type integer character boolean String Initial value 10 a true hello The following should be the expected screen output.11. 3 * 10 *2 / 15 – 2 + 4 ^ 2 ^ 2 3.D. write a program that outputs the number with the greatest value among the three. Number = 10 letter = a result = true str = hello 4.3 Output greatest value Given three numbers. number 1 = 10 number 2 = 23 number 3 = 5 The highest number is = 23 4. Use the conditional ?: operator that we have studied so far (HINT: You will need to use two sets of ?: to solve this).11. 20 and 45.E.1 Declaring and printing variables Given the table below. 1. Let the values of the three numbers be.J. 10. a / b ^ c ^ d – e + f – g * h + i 2.11 Exercises 4. Output to the screen the variable names together with the values.2 Getting the average of three numbers Create a program that outputs the average of three numbers.11. r ^ s * t / u – v + w ^ x – y++ Introduction to Programming I 99 . re-write them by writing some parenthesis based on the sequence on how they will be evaluated. The expected screen output is. 23 and 5.
*. } catch( IOException e ){ System.J. 3.out.io package in order to get input from the keyboard. } Introduction to Programming I 100 . the student should be able to: • • • Create an interactive Java program that gets input from the keyboard Use the BufferedReader class to get input from the keyboard using a console Use the JOptionPane class to get input from the keyboard using a graphical user interface 5. we will use the BufferedReader class found in the java. At the end of the lesson.E. let's make our programs more interactive by getting some input from the user. the first one is through the use of the BufferedReader class and the other one involves a graphical user interface by using JOptionPane. Add this at the top of your code: import java. and invoke the readLine() method to get input from the keyboard. In this section.in) ).2 Using BufferedReader to get input In this section.readLine().I 5 Getting Input from the Keyboard 5.1 Objectives Now that we've studied some basic concepts in Java and we've written some simple programs.io. Declare a temporary String variable to get the input. 2. Add this statement: BufferedReader dataIn = new BufferedReader( new InputStreamReader( System. Here are the steps to get input from the keyboard: 1.D. You have to type it inside a try-catch block. we'll be discussing two methods of getting input. try{ String temp = dataIn.println(“Error in getting input”).
out.IOException.io.BufferedReader. The statements can also be rewritten as. InputStreamReader and IOException which is inside the java.io. String name = "".IOException.I Here is the complete source code: import java.J. public class GetInputFromKeyboard { public static void main( String[] args ){ BufferedReader dataIn = new BufferedReader(new InputStreamReader( System.in) ). }catch( IOException e ){ System. the java.out. which will load all the classes found in the package. try{ name = dataIn.println("Error!"). The Java Application Programming Interface (API) contains hundreds of predefined classes that you can use in your programs. System. Just like in our example. import java.InputStreamReader.io package contains classes that allow programs to input and output data. import java.E. These classes are organized into what we call packages. and then we can use those classes inside our program.io.io. import java. import java. } Now let's try to explain each line of code: The statements. } } System.D.readLine().out.io. import java.io. Packages contain classes that have related purpose.io package.BufferedReader. import java. indicate that we want to use the classes BufferedReader.io.print("Please Enter Your Name:").println("Hello " + name +"!").*. Introduction to Programming I 101 .InputStreamReader.
try{ name = dataIn.I The next two statements.println("Error!"). We will cover more about this later in the course. System. BufferedReader dataIn = new BufferedReader(new InputStreamReader( System. the following block defines a try-catch block. Now.out.in) ). Now. Introduction to Programming I 102 .D.out. It is always good to initialize your variables as you declare them. public class GetInputFromKeyboard { public static void main( String[] args ){ were already discussed in the previous lesson. will be catched. We will cover more about exception handling in the latter part of this course. but for now.J. The variable name is initialized to an empty String "". we are declaring a variable named dataIn with the class type BufferedReader. This means we declare a class named GetInputFromKeyboard and we declare the main method. In the statement. The next line just outputs a String on the screen asking for the user's name.print("Please Enter Your Name:"). } This assures that the possible exceptions that could occur in the statement name = dataIn.readLine(). This is where we will store the input of the user.readLine().E. }catch( IOException e ){ System. we are declaring a String variable with the identifier name. String name = "". Don't worry about what the syntax means for now. just take note that you need to add this code in order to use the readLine() method of BufferedReader to get input from the user.
Introduction to Programming I 103 . gets input from the user and will return a String value. name = dataIn. dataIn.E.readLine(). System.out.J. This value will then be saved to our name variable.println("Hello " + name + "!"). which we will use in our final statement to greet the user.D.readLine(). the method call.I Now going back to the statement.
I 5.showInputDialog("Please enter your name").E.showMessageDialog(null. msg). name = JoptionPane. } Figure 5. JOptionPane makes it easy to pop up a standard dialog box that prompts users for a value or informs them of something. public class GetInputFromKeyboard { public static void main( String[] args ){ String name = "". String msg = "Hello " + name + "!".swing package.JOptionPane. JOptionPane. } This will output.D.3 Using JOptionPane to get input Another way to get input from the user is by using the JOptionPane class which is found in the javax.1: Getting Input Using JOptionPane Figure 5.J.3: Showing Message Using JOptionPane Introduction to Programming I 104 . import javax. Given the following code.swing.2: Input florence on the JOptionPane Figure 5.
The next line displays a dialog which contains a message and an OK button.showInputDialog("Please enter your name"). msg).swing package. name = JOptionPane. a textfield and an OK button as shown in the figure.showMessageDialog(null. import javax.I The first statement.D. which will display a dialog with a message. Introduction to Programming I 105 . String msg = "Hello " + name + "!". creates a JOptionPane input dialog.J. The statement. indicates that we want to import the class JOptionPane from the javax.*. JOptionPane. Now we create the welcome message.E. We can also write this as. which we will store in the msg variable.swing. import javax.JOptionPane. This returns a String which we will save in the name variable.swing.
4.1 Last 3 words (BufferedReader version) Using BufferedReader. ask for three words from the user and output those three words on the screen. For example.I 5.4.5: Second Input Figure 5.D.4 Exercises 5. For example.J. Enter word1:Goodbye Enter word2:and Enter word3:Hello Goodbye and Hello 5.2 Last 3 words (JOptionPane version) Using JOptionPane. Figure 5.6: Third Input Figure 5.E.7: Show Message Introduction to Programming I 106 .4: First Input Figure 5. ask for three words from the user and output those three words on the screen.
return) which allows redirection of program flow 6. for) which allow executing specific sections of code a number of times Use branching statements (break. At the end of the lesson. if( boolean_expression ) statement. The if-statement has the form. which allows us to change the ordering of how the statements in our programs are executed. statement2.I 6 Control Structures 6. or if( boolean_expression ){ statement1.J. In this section.E. } where.2 Decision Control Structures Decision control structures are Java statements that allows us to select and execute specific blocks of code while skipping other sections.D. Introduction to Programming I 107 . .2. the student should be able to: • • • Use decision control structures (if. else. we will be discussing control structures. . we have given examples of sequential programs.1 Objectives In the previous sections. .1 if statement The if-statement specifies that a statement (or block of code) will be executed if and only if a certain boolean statement is true. wherein statements are executed one after another in a fixed order. do-while. boolean_expression is either a boolean expression or boolean variable. switch) which allows selection of specific sections of code to be executed Use repetition control structures (while. 6. continue.
if( grade > 60 ){ System. //statement2.println("Congratulations!").out. Indent the statements inside the if-block.println("You passed!").E.For example.out.println("Congratulations!"). int grade = 68. } Coding Guidelines: 1. } Introduction to Programming I 108 . if( boolean_expression ){ //statement1. 2. System. That means that the execution of the condition should either result to a value of true or a false. or int grade = 68.out.J.D. The boolean_expression part of a statement should evaluate to a boolean value.1: Flowchart of If-Statement if( grade > 60 ) System. given the code snippet. Figure 6.I For example.
. .out.println("Congratulations!"). } else{ System.out. else System. if( grade > 60 ) System.println("Sorry you failed"). if( grade > 60 ){ System.J. . } Introduction to Programming I 109 . statement2. or can also be written as.println("Sorry you failed"). and a different statement if the condition is false.out. } else{ statement1.2 if-else statement The if-else statement is used when we want to execute a certain statement if a condition is true. or int grade = 68.E. .D. . if( boolean_expression ) statement. The if-else statement has the form. int grade = 68.out. System.I 6. .2.out.println("Congratulations!"). else statement. if( boolean_expression ){ statement1. } For example. statement2. given the code snippet.println("You passed!").
.E. This means that you can have other if-else blocks inside another if-else block.D.. } } else{ .2: Flowchart of If-Else Statement Coding Guidelines: 1. To avoid confusion.For example.. if( boolean_expression ){ if( boolean_expression ){ . 2. You can have nested if-else blocks. always place the statement or statements of an if or if-else block inside brackets {}. } Introduction to Programming I 110 .J. .I Figure 6.
else if( boolean_expression2 ) statement2. else statement3.I 6. Figure 6. Take note that you can have many else-if blocks after an if-statement.2. if boolean_expression1 is true. The else-block is optional and can be omitted.3: Flowchart of If-Else-If Statement Introduction to Programming I 111 . then the program executes statement1 and skips the other statements. In the example shown above. If boolean_expression2 is true. if( boolean_expression1 ) statement1. The if-else if statement has the form.E. This cascading of structures allows us to make more complex selections.D.J. then the program executes statement 2 and skips to the statements following statement3.3 if-else-if statement The statement in the else-clause of an if-else block can be another if-else structures.
2. //WRONG int number = 0. if( number == 0 ){ //some statements here } 3.out. if( number ){ //some statements here } The variable number does not hold a Boolean value. } else if( grade > 60 ){ System. For example. The condition inside the if-statement does not evaluate to a boolean value.E. } else{ System. Introduction to Programming I 112 .J. if( number = 0 ){ //some statements here } This should be written as.println("Very good!"). //WRONG int number = 0. Using = instead of == for comparison. if( grade > 90 ){ System.out. Writing elseif instead of else if.println("Sorry you failed").D.I For example. For example.println("Very good!").out. } 6.4 Common Errors when using the if-else statements: 1. int grade = 68. given the code snippet. //CORRECT int number = 0.2.
0.E.out.out. } else if( (grade < 80) && (grade >= 60)){ System. } else if( (grade < 90) && (grade >= 80)){ System.out.out.J. you failed. } else{ System.2.D.println("Study harder!" )."). } } } Introduction to Programming I 113 .println( "Excellent!" ).5 Example for if-else-else if public class Grade { public static void main( String[] args ) { double grade = 92.println("Good job!" ).I 6.println("Sorry. if( grade >= 90 ){ System.
NOTES: • Unlike with the if statement. // break.2. . all the statements associated with that case are executed. case case_selector2: statement1.I 6. // statement2. the statements associated with the succeeding cases are also executed. and jumps to the case whose selector matches the value of the expression. //block 2 . Java first evaluates the switch_expression. switch( switch_expression ){ case case_selector1: statement1. Introduction to Programming I 114 . we use a break statement as our last statement. default: statement1. // statement2.D. . are unique integer or character constants. // break. // break. The switch construct allows branching on multiple outcomes. .E. .6 switch statement Another way to indicate a branch is through the switch keyword. . . } where. the multiple statements are executed in the switch statement without needing the curly braces. switch_expression is an integer or character expression and. case_selector2 and so on.J. //block n . The program executes the statements in order from that point on until a break statement is encountered. The switch statement has the form. • When a case in a switch statement has been matched. Take note however. • To prevent the program from executing statements in the subsequent cases. If none of the cases are satisfied. . skipping then to the first statement after the end of the switch structure. . that the default part is optional. the default block is executed. Not only that. . // statement2. When a switch is encountered. case_selector1. //block 1 . A switch statement can have no default block.
You can decide which to use. An if statement can be used to make decisions based on ranges of values or conditions. 2. Deciding whether to use an if statement or a switch statement is a judgment call.4: Flowchart of Switch Statements Introduction to Programming I 115 .J.E. Figure 6. based on readability and other factors.D. Also.I Coding Guidelines: 1. the value provided to each case statement must be unique. whereas a switch statement can make decisions based only on a single integer or character value.
J.E.D.I
6.2.7 Example for switch
public class Grade { public static void main( String[] args ) { int grade = 92; switch(grade){ case 100: System.out.println( "Excellent!" ); break; case 90: System.out.println("Good job!" ); break; case 80: System.out.println("Study harder!" ); break; default: System.out.println("Sorry, you failed."); }
}
}
Introduction to Programming I
116
J.E.D.I
6.3 Repetition Control Structures
Repetition control structures are Java statements that allows us to execute specific blocks of code a number of times. There are three types of repetition control structures, the while, do-while and for loops.
6.3.1 while loop
The while loop is a statement or block of statements that is repeated as long as some condition is satisfied. The while statement has the form, while( boolean_expression ){ statement1; statement2; . . . } The statements inside the while loop are executed as long as the boolean_expression evaluates to true. For example, given the code snippet, int i = 4; while ( i > 0 ){ System.out.print(i); i--; } The sample code shown will print 4321 containing the statement i--; is removed, that does not terminate. Therefore, when control structures, make sure that you add terminate at some point. on the screen. Take note that if the line this will result to an infinite loop, or a loop using while loops or any kind of repetition some statements that will allow your loop to
Introduction to Programming I
117
J.E.D.I
The following are other examples of while loops, Example 1: int x = 0; while (x<10) { System.out.println(x); x++; } Example 2: //infinite loop while(true) System.out.println(“hello”); Example 3: //no loops // statement is not even executed while (false) System.out.println(“hello”);
Introduction to Programming I
118
J.E.D.I
6.3.2 do-while loop
The do-while loop is similar to the while-loop. The statements inside a do-while loop are executed several times as long as the condition is satisfied. The main difference between a while and do-while loop is that, the statements inside a do-while loop are executed at least once. The do-while statement has the form, do{ statement1; statement2; . . . }while( boolean_expression ); The statements inside the do-while loop are first executed, and then the condition in the boolean_expression part is evaluated. If this evaluates to true, the statements inside the do-while loop are executed again. Here are a few examples that uses the do-while loop: Example 1: int x = 0; do { System.out.println(x); x++; }while (x<10); This example will output 0123456789 on the screen. Example 2: //infinite loop do{ System.out.println(“hello”); } while (true); This example will result to an infinite loop, that prints hello on screen. Example 3: //one loop // statement is executed once do System.out.println(“hello”); while (false); This example will output hello on the screen.
Introduction to Programming I
119
J.E.D.I
Coding Guidelines: 1. Common programming mistakes when using the do-while loop is forgetting to write the semi-colon after the while expression. do{ ... }while(boolean_expression) //WRONG->forgot semicolon ; 2. Just like in while loops, make sure that your do-while loops will terminate at some point.
6.3.3 for loop
The for loop, like the previous loops, allows execution of the same code a number of times. The for loop has the form, for (InitializationExpression; LoopCondition; StepExpression){ statement1; statement2; . . . } where, InitializationExpression -initializes the loop variable. LoopCondition - compares the loop variable to some limit value. StepExpression - updates the loop variable.
A simple example of the for loop is, int i; for( i = 0; i < 10; i++ ){ System.out.print(i); } In this example, the statement i=0, first initializes our variable. After that, the condition expression i<10 is evaluated. If this evaluates to true, then the statement inside the for loop is executed. Next, the expression i++ is executed, and then the condition expression is again evaluated. This goes on and on, until the condition expression evaluates to false. This example, is equivalent to the while loop shown below, int i = 0; while( i < 10 ){ System.out.print(i); i++; }
Introduction to Programming I
120
J.E.D.I
6.4 Branching Statements
Branching statements allows us to redirect the flow of program execution. Java offers three branching statements: break, continue and return.
6.4.1 break statement
The break statement has two forms: unlabeled (we saw its unlabeled form in the switch statement) and labeled. 6.4.1.1 Unlabeled break statement The unlabeled break terminates the enclosing switch statement, and flow of control transfers to the statement immediately following the switch. You can also use the unlabeled form of the break statement to terminate a for, while, or do-while loop. For example, String names[] = {"Beah", "Bianca", "Lance", "Belle", "Nico", "Yza", "Gem", "Ethan"}; String boolean searchName = "Yza"; foundName = false;
for( int i=0; i< names.length; i++ ){ if( names[i].equals( searchName )){ foundName = true; break; } } if( foundName ){ System.out.println( searchName + " found!" ); } else{ System.out.println( searchName + " not found." ); } In this example, if the search string "Yza" is found, the for loop will stop and flow of control transfers to the statement following the for loop.
Introduction to Programming I
121
J.E.D.I
6.4.1.2 Labeled break statement The labeled form of a break statement terminates an outer statement, which is identified by the label specified in the break statement. The following program searches for a value in a two-dimensional array. Two nested for loops traverse the array. When the value is found, a labeled break terminates the statement labeled search, which is the outer for loop. int[][] numbers = {{1, 2, 3}, {7, 8, 9}}; int searchNum = 5; boolean foundNum = false; searchLabel: for( int i=0; i<numbers.length; i++ ){ for( int j=0; j<numbers[i].length; j++ ){ if( searchNum == numbers[i][j] ){ foundNum = true; break searchLabel; } } } if( foundNum ){ System.out.println( searchNum + " found!" ); } else{ System.out.println( searchNum + " not found!" ); } The break statement terminates the labeled statement; it does not transfer the flow of control to the label. The flow of control transfers to the statement immediately following the labeled (terminated) statement. {4, 5, 6},
Introduction to Programming I
122
The following example counts the number of "Beah"s in the array. Introduction to Programming I 123 . outerLoop: for( int i=0.2.println("Inside for(i) loop").J.out.D. //message2 In this example.2. int count = 0.println("There are " + count + " Beahs in the list"). i++ ){ if( !names[i].1 Unlabeled continue statement The unlabeled form skips to the end of the innermost loop's body and evaluates the boolean expression that controls the loop. basically skipping the remainder of this iteration of the loop. "Lance". for( int i=0. //skip next statement } } count++. "Beah"}. You can use the continue statement to skip the current iteration of a for.println("Inside for(j) loop"). System. i<5. //message1 if( j == 2 ) continue outerLoop.length.E.out. String names[] = {"Beah".4. i<names. j++ ){ System. "Bianca".4. while or do-while loop.out. 6. message 2 never gets printed since we have the statement continue outerloop which skips the iteration. i++ ){ for( int j=0. } } System.4.2 continue statement The continue statement has two forms: unlabeled and labeled.equals("Beah") ){ continue.I 6. 6. j<5.2 Labeled continue statement The labeled form of the continue statement skips the current iteration of an outer loop marked with the given label.
J. Introduction to Programming I 124 .4.I 6. use the form of return that doesn't return a value.E. The flow of control returns to the statement that follows the original method call. return "Hello". We will cover more about return statements later when we discuss about methods. return. For example. For example. To return a value.D. simply put the value (or an expression that calculates the value) after the return keyword. The return statement has two forms: one that returns a value and one that doesn't. The data type of the value returned by return must match the type of the method's declared return value. or return ++count.3 return statement The return statement is used to exit from the current method. When a method is declared void.
If the user inputs a number that is not in the range.3 Hundred Times Create a program that prints your name a hundred times. Introduction to Programming I 125 . Together with the average. otherwise output :-(. 1.5. 2. 6.5 Exercises 6. Use a switch statement to solve this problem 6. and System. 6. a do-while loop and a for-loop. "Invalid number".D.5. Use BufferedReader to get input from the user. Output the average of the three exams. also include a smiley face in the output if the average is greater than or equal to 60.1 Grades Get three exam grades from the user and compute the average of the grades.I 6.out to output the result.J.5. Do three versions of this program using a while loop. and output the equivalent of the number in words. Use an if-else statement to solve this problem 2. output.E. Do three versions of this program using a while loop. 1.2 Number in words Get a number as input from the user.5. Use JOptionPane to get input from the user and to output the result. a do-while loop and a for-loop. The number inputted should range from 1-10.4 Powers Compute the power of a number given the base and exponent.
number3 = 3. Think of an array as a stretched variable – a location that still has one identifier name. divided into a number of slots. At the end of the lesson. but can hold more than one value. there is one capability wherein we can use one variable to store a list of data and manipulate them more efficiently. int number2. we will be discussing about Java Arrays. we often use a unique identifier or name and a datatype. we have here three variables of type int with different identifiers for each variable. number1 = 1.2 Introduction to arrays In the previous sections. it seems like a tedious task in order to just initialize and use the variables especially if they are used for the same purpose. and then we are going to discuss on how to declare and use them.1 Objectives In this section. As you can see. int number1. For example. This type of variable is called an array.1: Example of an Integer Array An array stores multiple data items of the same datatype. number2 = 2. Introduction to Programming I 126 . we have discussed on how to declare different variables using the primitive data types. int number3. In Java and other programming languages. the student should be able to: • • • • Declare and create arrays Access array elements Determine the number of elements in an array Declare and create multidimensional arrays 7. we call it by its identifier name.J.E. in a contiguous block of memory. In order to use the variable. Figure 7. First.D. In declaring variables.I 7 Java Arrays 7. we are going to define what arrays are.
2: Instantiating Arrays Introduction to Programming I 127 . We will cover more about instantiating objects and constructors later. the declaration tells the Java Compiler that the identifier ages will be used as the name of an array containing integers. This process in Java is called instantiation (the Java word for creates). After declaring. you list the data type. For example. we need to use a constructor for this. that the size of an array cannot be changed once you've initialized it. In the example. int ages[]. can also be written as. Instead of using the new keyword to instantiate an array. //declaration int ages[]. For example. or.3 Declaring Arrays Arrays must be declared like all variables. //instantiate object ages = new int[100]. or you can place the brackets after the identifier.E.J. construct and assign values at once. you can also automatically declare. //declare and instantiate object int ages[] = new int [100]. int []ages.I 7.D. For example. When declaring an array. In order to instantiate an object. and to create or instantiate a new array containing 100 elements. we must create the array and specify its length with a constructor statement. Figure 7. Take note. followed by the identifier name. followed by a set of square brackets[].
This array contains 4 elements that are //initialized to values {true. 90. false }. 75}. “Sat”. //creates an array of Strings with identifier days and //initialized.E. 80. “Wed”. “Thu”. true. This array contains 7 elements String days[] = { “Mon”. //creates an array of boolean variables with ientifier //results. 75}.I Examples are. false} boolean results[] ={ true. double []grades = {100.J. “Tue”. Introduction to Programming I 128 .D. true. 90. 80. false. //creates an array of 4 double variables initialized //to the values {100. “Sun”}. false. “Fri”.
given the array we declared a while ago. Take note that the elements inside your array is from 0 to (sizeOfArray-1).E. int []arr = new int[100]. i<100. is preferred over. They begin with zero and progress sequentially by whole numbers to the end of the array.print( ages[i] ). 3. i++ ){ System. Introduction to Programming I 129 . An index number or subscript is assigned to each member of the array. for( int i=0. you use a number called an index or a subscript. 2. } } Coding Guidelines: } 1. Therefore. The following is a sample code on how to print all the elements in the array. For example.print(ages[99]). so our code is shorter. Index numbers are always integers. Note that there is no array element arr[n]! This will result in an array-index-out-of-bounds exception.I 7.4 Accessing an array element To access an array element. You cannot resize an array. you must populate the String arrays explicitly. arr = new int[100]. the stored value of each member of the array will be initialized to zero for number data. public class ArraySample{ public static void main( String[] args ){ int[] ages = new int[100]. reference data types such as Strings are not initialized to blanks or an empty string “”.D.out.J. This uses a for loop. we have //assigns 10 to the first element in the array ages[0] = 10. However. It is usually better to initialize or instantiate the array right away after you declare it. allowing the program and the programmer to access individual values when necessary. //prints the last element in the array System. Take note that once an array is declared and constructed. The elements of an n-element array have indexes from 0 to n-1. int []arr. For example. the declaration.out. or a part of the array.
The length field of an array returns the size of the array. //declare a constant .length For example.length. given the previous example.. you can use the length field of an array.I 7. final int ARRAY_SIZE = 1000. It can be used by writing. When creating for loops to process the elements of an array. Declare the sizes of arrays in a Java program using named constants to make them easy to change.print( ages[i] ). } } Coding Guidelines: } 1. Introduction to Programming I 130 . For example. we can re-write it as. 2. use the array object's length field in the condition statement of the for loop. public class ArraySample { public static void main( String[] args ){ int[] ages = new int[100]. arrayName. This will allow the loop to adjust automatically for different-sized arrays.J.5 Array length In order to get the number of elements in an array. int[] ages = new int[ARRAY_SIZE]. i<ages.D.out. for( int i=0. i++ ){ System.E..
we write. { "fido". Introduction to Programming I 131 .I 7. Multidimensional arrays are declared by appending the appropriate number of bracket pairs after the array name. "black"} }.J.E. { "Kristin". To access an element in a multidimensional array is just the same as accessing the elements in a one dimensional array. to access the first element in the first row of the array dogs.6 Multidimensional Arrays Multidimensional arrays are implemented as arrays of arrays. { "toby". For example. // integer array 512 x 128 elements int[][] twoD = new int[512][128].print( dogs[0][0] ). "gray"}. This will print the String "terry" on the screen. "white" }. System. // String array 4 rows x 2 columns String[][] dogs = {{ "terry".D.out. "brown" }. For example. // character array 8 x 16 x 24 char[][][] threeD = new char[8][16][24].
"456-3322".7. print all the contents of the array. # : 456-3322 Address : Manila Introduction to Programming I 132 .E. {"Becca".I 7. "983-3333".J.D.2 Greatest number Using BufferedReader or JOptionPane. String days[] = {“Monday”. 7. For Example. Print the following entries on screen in the following format: Name : Florence Tel. # : 983-3333 Address : Quezon City Name : Becca Tel.7. "Manila"}. {"Joyce".7.}. Output on the screen the number with the greatest value. Using a while-loop. Use an array to store the values of these 10 numbers.1 Days of the Week Create an array of Strings which are initialized to the 7 days of the week. (do the same for do-while and forloop) 7.7 Exercises 7.3 Addressbook Entries Given the following multidimensional array that contains addressbook entries: String entry = {{"Florence". ask for 10 numbers from the user. # : 735-1234 Address : Manila Name : Joyce Tel. "Manila"}}. “Tuesday”…. "735-1234". "Quezon City"}.
Introduction to Programming I 133 . that sorts five numbers. suppose you have a Java application.2 Command-line arguments A Java application can accept any number of arguments from the command-line. called Sort.I 8 Command-line Arguments 8. Command-line arguments allow the user to affect the operation of an application for one invocation.E. you run it like this: Figure 8.1: Running with Command-Line Arguments Take note that the arguments are separated by spaces.1 Objectives In this section. the student should be able to: • • • Know and explain what a command-line argument is Get input from the user using command-line arguments Learn how to pass arguments to your programs in Netbeans 8. we will study on how to process input from the command-line by using arguments pass onto a Java program.D. For example.J. At the end of the lesson. The user enters command-line arguments when invoking the application and specifies them after the name of the class to run.
D. You can derive the number of command-line arguments with the array's length attribute. "3". int numberOfArgs = args. when you invoke an application. the command-line arguments passed to the Sort application is an array that contains five strings which are: "5".I In the Java language. such as "34". If your program needs to support a numeric command-line argument.parseInt(args[0]). the runtime system passes the command-line arguments to the application's main method via an array of Strings. always check if the number of arguments before accessing the array elements so that there will be no exception generated. For example. Remember the declaration for the main method. public static void main( String[] args ) The arguments that are passed to your program are saved into an array of String with the args identifier. Here's a code snippet that converts a command-line argument to an integer. if (args.E.length. "4". it must convert a String argument that represents a number. In the previous example.length > 0){ firstArg = Integer. "2" and "1". to a number. } parseInt throws a NumberFormatException (ERROR) if the format of args[0] isn't valid (not a number). Introduction to Programming I 134 . Each String in the array contains one of the command-line arguments. Coding Guidelines: Before using command-line arguments.J. int firstArg = 0.
3 Command-line arguments in Netbeans To illustrate on how to pass some arguments to your programs in Netbeans. Now.println("First Argument="+ args[0]).out.I 8. Click on Projects (encircled below). Figure 8. Copy the code shown above and compile the code. System. } } Now.out.D.2: Opening Project File Introduction to Programming I 135 .println("Number of arguments=" + args.J. public class CommandLineExample { public static void main( String[] args ){ System. run netbeans and create a new project and name this CommandLineExample. let us create a Java program that will print the number of arguments and the first argument passed to it.E. follow these steps to pass arguments to your program using Netbeans.length).
and a popup menu will appear.4: Properties Dialog Introduction to Programming I 136 .J. Figure 8.I Right-click on the CommandLineExample icon. Click on Properties.D. Figure 8.3: Opening Properties The Project Properties dialog will then appear.E.
type the arguments you want to pass to your program.E.5: Click On Running Project On the Arguments textbox.D. Figure 8. Then. In this case we typed in the arguments 5 4 3 2 1. click on Run-> Running Project. click on the OK button.I Now. Figure 8.J.6: Set the Command-Line Arguments Introduction to Programming I 137 .
I Now try to RUN your program.D. the output to your program is the number of arguments which is 5.7: Running the Program in with the Shortcut Button As you can see here. Figure 8. and the first argument which is 5.E. Figure 8.8: Program Output Introduction to Programming I 138 .J.
4 Exercises 8. product and quotient of the two numbers.J. For example. difference.4. if the user entered. java ArithmeticOperation 20 4 your program should print sum = 24 difference = 16 product = 80 quotient = 5 Introduction to Programming I 139 . java Hello world that is all your program should print Hello world that is all 8.I 8.D.1 Print arguments Get input from the user using command-line arguments and print all the arguments to the screen.4.2 Arithmetic Operations Get two numbers from the user using command-line arguments and print sum.E. if the user entered. For example.
Comparison. people and so on. At the end of the lesson. These objects are characterized by their properties (or attributes) and behaviors. braking and accelerating. we will discuss later on how to create your own classes. Later on. such as cars.E. we will introduce some basic concepts of object-oriented programming. For example. type of transmission.D. the student should be able to: • • • • • • • Explain object-oriented programming and some of its concepts Differentiate between classes and objects Differentiate between instance variables/methods and class(static) variables/methods Explain what methods are and how to call and pass parameters to methods Identify the scope of a variable Cast primitive data types and objects Compare objects and determine the class of an objects 9. we can define different properties and behavior of a lion.1 Objectives In this section. For now. we can find many objects around us.I 9 Working with the Java Class Library 9. Please refer to the table below for the examples. Object Car Properties type of transmission manufacturer color Weight Color hungry or not hungry tamed or wild Table 17: Example of Real-life Objects Behavior turning braking accelerating roaring sleeping hunting Lion Introduction to Programming I 140 .2 Introduction to Object-Oriented Programming Object-Oriented programming or OOP revolves around the concept of objects as the basic elements of your programs. a car object has the properties. we will discuss the concept of classes and objects. and how to use these classes and their members. lion. When we compare this to the physical world. conversion and casting of objects will also be covered. we will focus on using classes that are already defined in the Java class library.J. Its behaviors are turning. manufacturer and color. Similarly.
Car Class Instance Variables Plate Number Color Manufacturer Current Speed Blue Object Car A ABC 111 Mitsubishi 50 km/h Accelerate Method Turn Method Brake Method Table 18: Example of Car class and its objects Object Car B XYZ 123 Red Toyota 100 km/h When instantiated. let us discuss an example. and it also consists of a set of methods (behavior) that describes how an object behaves.D. an object is a software bundle of variables and related methods. and current speed which are filled-up with corresponding values in objects Car A and Car B. Each object is composed of a set of data (properties/attributes) which are variables describing the essential characteristics of the object. manufacturer. the method implementations are shared among objects of the same class. Introduction to Programming I Instance Methods 141 . Software programmers can use a class over and over again to create many objects. 9. color. Fields specifiy the data types defined by the class. while methods specify the operations. Turn and Brake. However. The variables and methods in a Java object are formally known as instance variables and instance methods to distinguish them from class variables and class methods. The class is the fundamental structure in object-oriented programming. which will be discussed later. To differentiate between classes and objects. It can be thought of as a template.E. the objects in the physical world can easily be modeled as software objects using the properties as data and the behaviors as methods. It consists of two types of members which are called fields (properties or attributes) and methods.1 Difference Between Classes and Objects In the software world. each object gets a fresh set of state variables.J.3 Classes and Objects 9. Thus. In the table shown below. An object is an instance of the class. a prototype or a blueprint of an object. Car A and Car B are objects of the Car class.I With these descriptions. an object is a software component whose structure is similar to objects in the real world. Classes provide the benefit of reusability. What we have here is a Car Class which can be used to define several Car Objects.3. The Car has also some methods Accelerate. The class has fields plate number. These data and methods could even be used in programming games or interactive software to simulate the real-world objects! An example would be a car software object in a racing game or a lion software object in an educational interactive software zoo for kids.
They are also called static member variables. it is also possible to define class variables. To clearly describe class variables. 9. By placing a boundary around the properties and methods of our objects. This means that it has the same value for all the objects in the same class. all of the objects of the Car class will have the value 2 for their Count variable.3. which are variables that belong to the whole class.J.D. We will learn more about how Java implements encapsulation as we discuss more about classes. let's go back to our Car class example. we can prevent our programs from having side effects wherein programs have their variables changed in unexpected ways. If we change the value of Count to 2. Suppose that our Car class has one class variable called Count.3. Car Class Instance Variables Plate Number Color Manufacturer Current Speed Blue Mitsubishi 50 km/h Count = 2 Accelerate Method Turn Method Brake Method Table 19: Car class' methods and variables Object Car A ABC 111 Red Toyota Object Car B XYZ 123 100 km/h Introduction to Programming I Instance Methods Variable Class 142 . We can prevent access to our object's data by declaring them declaring them in a certain way such that we can control access to them.2 Encapsulation Encapsulation is the method of hiding certain elements of the implementation of a certain class.I 9.E.3 Class Variables and Methods In addition to the instance variables.
I 9. you actually invoke the class' constructor. Figure 9. When you create an object. str2 = new String(“Hello world!”).4 Class Instantiation To create an object or an instance of a class. String str2 = "Hello". String or also equivalent to. if you want to create an instance of the class String.3.E.1: Classs Instantiation The new operator allocates a memory for that object and returns a reference of that memory location to you. The constructor is a method where you place all the initializations. Introduction to Programming I 143 .D. we write the following code. it has the same name as the class. For example.J. we use the new operator.
and that is the main() method. it goes back to the method that called it. Taking a problem and breaking it into small.4 Methods 9. why do we need to create methods? Why don't we just place all the code inside one big method? The heart of effective problem solving is in problem decomposition. In Java. Introduction to Programming I 144 . We can do this in Java by creating methods to solve a specific part of the problem. • After the method has finished execution.J. we only have one method.D. we can define many methods which we can call from different methods. A method is a separate piece of code that can be called by a main program or any other method to perform some specific function.I 9.E. The following are characteristics of methods: • It can return one or no values • It may accept as many parameters it needs or no parameter at all. Now. manageable pieces is critical to writing large programs.1 What are Methods and Why Use Methods? In the examples we discussed before.4. Parameters are also called function arguments.
E. String char String str1 = "Hello". Two strings are considered equal ignoring case if they are of the same length. The first character of the sequence is at index 0. nameOfObject.4. Table 20: Sample Methods of class String Using the methods. Later on.equalsIgnoreCase( str1 ).J. public boolean equalsIgnoreCase Compares this String to another String. ignoring (String anotherString) case considerations. Method declaration public char charAt(int index) Definition Returns the character at the specified index. we will create our own methods.nameOfMethod( parameters ). and corresponding characters in the two strings are equal ignoring case. we write the following. Let's take two sample methods found in the class String. and so on.I 9. to illustrate how to call methods. let's use the String class as an example. You can use the Java API documentation to see all the available methods in the String class. as for array indexing. To call an instance method.charAt(0). //this will return a boolean value true boolean result = str1. Introduction to Programming I 145 .D.2 Calling Instance Methods and Passing Variables Now. //will return the character H //and store it to variable x str2 = "hello". the next at index 1.1. An index ranges from 0 to length() . let us use what is available. x = str2. but for now.
pass-byreference. //call method test //and pass i to method test test( i ).I 9. Pass i as parameter which is copied to j } //print the value of i.J. it will not affect the variable value if i in main since it is a different copy of the variable.4. The method cannot accidentally modify the original argument even if it modifies the parameters during calculations.1 Pass-by-value When a pass-by-value occurs. we called the method test and passed the value of i as parameter. Introduction to Programming I 146 . we already tried passing variables to methods.out.E.3. By default.println( i ). //print the value of i System. } In the given example. Since j is the variable changed in the test method. 9.out. However. i not changed System.println( i ).3 Passing Variables in Methods In our examples. all primitive data types when passed to a method are pass-by-value. The value of i is copied to the variable of the method j. } public static void test( int j ){ //change value of parameter j j = 33. For example. public class TestPassByValue { public static void main( String[] args ){ int i = 10. the method makes a copy of the value of the variable passed to the method. we haven't differentiated between the different types of variable passing in Java.D. the first one is pass-by-value and then.4. There are two types of passing data to methods.
out. 12}. the method can modify the actual object that the reference is pointing to. However.J. } //call test and pass reference to array test( ages ). the reference to an object is passed to the calling method. } } public static void test( int[] arr ){ //change values of array for( int i=0.out. the method makes a copy of the reference of the variable passed to the method. the location of the data they are pointing to is the same.length. This means that.3. i++ ){ System. For example. } } Introduction to Programming I 147 . 11. since.4. Pass ages as parameter which is copied to variable arr } //print array values again for( int i=0.length.E.I 9. i<ages. unlike in pass-by-value.println( ages[i] ). i<ages. class TestPassByReference { public static void main( String[] args ){ //create an array of integers int []ages = {10. i++ ){ arr[i] = i + 50. i++ ){ System. although different references are used in the methods.println( ages[i] ). i<arr.length. //print array values for( int i=0.2 Pass-by-reference When a pass-by-reference occurs.D.
D.println(“Hello world”). Examples of static methods.out. //prints data to screen System. to an integer int i = Integer.J.parseInt(“10”). //Returns a String representation of the integer argument as an //unsigned integer base 16 String hexEquivalent = Integer. 9. Classname. Static methods are distinguished from instance methods in a class definition by the keyword static. Static methods belongs to the class as a whole and not to a certain instance (or object) of a class. you cannot write a standard swap method to swap objects. Introduction to Programming I 148 .4 Calling Static Methods Static methods are methods that can be invoked without instantiating a class (means without invoking the new keyword). Take note that Java manipulates objects 'by reference.4. //converts the String 10. just type.staticMethodName(params).E.2: Pass-by-reference example Coding Guidelines: A common misconception about pass-by-reference in Java is when creating a swap method using Java references.'" As a result.' but it passes object references to methods 'by value.toHexString( 10 ). To call a static method. we've used so far in our examples are.I Figure 9.
E.. they are visible (i. The scope is determined by where the variable declaration is placed in the program. If you declare variables in the outer block. and the inner curly braces is called inner blocks.D and E. n = 0. m is D. k is C. Given the variables i. public class ScopeExample { public static void main( String[] args ){ int i = 0.j. int j = 0. The outer curly braces is called the outer blocks. int k = 0.m and n. //. The scope determines where in the program the variable is accessible. For example.}.D.5 Scope of a variable In addition to a variable's data type and name.C.J.. you cannot expect the outer block to see it.k. m = 0. starting from the point where it is declared. To simplify things. and the five scopes A. if you declare variables in the inner block. we have the following scopes for each variable: The The The The The scope scope scope scope scope of of of of of variable variable variable variable variable i is A. some code here B A { int int E } } The code we have here represents five scopes indicated by the lines and the letters representing the scope.B. D C Introduction to Programming I 149 . However. just think of the scope as anything between the curly braces {. usable) by the program lines inside the inner blocks. given the following code snippet. A variable's scope is inside the block where it is declared. The scope also determines the lifetime of a variable or how long the variable can exist in memory.e. a variable has scope.. n is E.4.. and in the inner blocks. j is B.I 9.
//print array values for( int i=0. ages[] . } B A C } E } public static void test( int[] arr ){ //change values of array for( int i=0. i<arr. given the two methods main and test in our previous examples. } } D In the main method.D. } //call test and pass reference to array test( ages ).length.out.scope E Introduction to Programming I 150 .scope B i in C – scope C In the test method. arr[] i in E .println( ages[i] ). class TestPassByReference { public static void main( String[] args ){ //create an array of integers int []ages = {10. i++ ){ arr[i] = i + 50. //print array values again for( int i=0.out. i++ ){ System.I Now. i++ ){ System.println( ages[i] ). the scope ofthe variables are. 11.J.length. the scope of the variables are. i<ages. 12}.length.scope A i in B .E.scope D . i<ages.
For the second System. System. it prints the value of the first test variable since it is the variable seen at that scope. Coding Guidelines: Avoid having variables of the same name declared inside one method to avoid confusion.J..out. your compiler will generate an error since you should have unique names for your variables in one block.print is invoke. } When the first System.out. Introduction to Programming I 151 . int test = 0. //.out.out. int test = 20. However. only one variable with a given identifier or name can be declared in a scope.E. { } int test = 10. you can have two variables of the same name. System. For example.D. That means that if you have the following declaration. if they are not declared in the same block.print( test ).print.print( test ). the value 20 is printed since it is the closest test variable seen at that scope.I When declaring variables.some code here { int test = 20.
System. and Java adopted this as part of its character support. Converting and Comparing Objects In this section. double numDouble = numInt.I 9.print( valInt ).5 Casting. 9. the cast (char)i produces the character value 'A'.E.1 Casting Primitive Types Casting between primitive types enables you to convert the value of one data from one type to another primitive type. The numeric code associated with a capital A is 65. and that is the boolean data type. A character can be used as an int because each character has a corresponding numeric code that represents its position in the character set. An example of typecasting is when you want to store an integer data to a variable of data type double. int valInt = valChar.D.5. If the variable i has the value 65. char valChar = 'A'. //explicit cast: output 65 Introduction to Programming I 152 . We will also learn how to convert primitive data types to objects and vice versa. we are going to learn how to compare objects. //implicit cast In this example. we are going to learn how to do typecasting. This commonly occurs between numeric types. For example. And finally. int numInt = 10. Typecasting or casting is the process of converting a data of a certain data type to another data type. the data is implicitly casted to data type double. For example.out. since the destination variable (double) holds a larger value than what we will place inside it. There is one primitive data type that we cannot do casting though. Another example is when we want to typecast an int to a char value or vice versa.J. according to the ASCII character set.
E. For example. double valDouble = 10. dataType. int int result = (int)(x/y). we must use an explicit cast. //convert valDouble to int type double x = 10.I When we convert a data that has a large type to a smaller type. int valInt = (int)valDouble. is an expression that results in the value of the source type.12. is the name of the data type you're converting to value. int y = 2.J.2. Explicit casts take the following form: (dataType)value where. //typecast result of operation to Introduction to Programming I 153 .D.
but you gain all the methods and variables that the subclass defines. There is a catch. We'll cover more about inheritance later. some objects might not need to be cast explicitly. You can pass an instance of any class for the Object argument because all Java classes are subclasses of Object.J. You won't lose any information in the cast. Introduction to Programming I 154 . one of type Object and another of type Window. because a subclass contains all the same information as its superclass. This is true anywhere in a program. To use superclass objects where subclass objects are expected. To cast an object to another class. If you had a variable defined as class Window. consider a method that takes two arguments. (classname)object where.2 Casting Objects Instances of classes also can be cast into instances of other classes. For example. however: Because subclasses contain more behavior than their superclasses. is a reference to the source object. is the name of the destination class object. you can use an instance of a subclass anywhere a superclass is expected. there's a loss in precision involved. For example. you must cast them explicitly. For the Window argument. you use the same operation as for primitive types: To cast. Analogous to converting a primitive value to a larger type. Errors occur if you try to call methods that the destination object doesn't have.I 9.5. not just inside method calls. such as Dialog. In particular. if you have an operation that calls methods in objects of the class Integer. Figure 9.D. and Frame. FileDialog. you can pass in its subclasses. with one restriction: The source and destination classes must be related by inheritance.3: Sample Class Hierarchy This is true in the reverse. Those superclass objects might not have all the behavior needed to act in place of a subclass object. you could assign objects of that class or any of its subclasses to that variable without casting.E. one class must be a subclass of the other. and you can use a superclass when a subclass is expected. classname. using an object of class Number won't include many methods specified in Integer.
J. VicePresident veep = new VicePresident().I • Note: that casting creates a reference to the old object of the type classname. // no cast needed for upward use veep = (VicePresident)emp. // must cast explicitlyCasting Introduction to Programming I 155 . the old object continues to exist as it did before. emp = veep.E. which here defines that the VicePresident has executive washroom privileges.D. VicePresident is a subclass of Employee with more information. Figure 9. Employee emp = new Employee().4: Class Hierarchy for superclass Employee The following example casts an instance of the class VicePresident to an instance of the class Employee.
lang package includes classes that correspond to each primitive data type: Float. the java. Byte.D. or vice versa. Double instead of double. //The following statement converts an Integer object to // its primitive data type int. As an alternative.I 9. and the like). Boolean. and you can't automatically cast between the two or use them interchangeably. which is used in method definitions to indicate that the method does not return a value. Most of these classes have the same names as the data types. // A common translation you need in programs // is converting a String to a numeric type. Examples: //The following statement creates an instance of the Integer // class with the integer value 7801 (primitive -> Object) Integer dataCount = new Integer(7801).E. two classes have names that differ from the corresponding data type: Character is used for char variables and Integer for int variables.intValue(). except that the class names begin with a capital letter (Short instead of short. such as an int // Object->primitive String pennsylvania = "65000". (Called Wrapper Classes) Java treats the data types and their class versions very differently.J. Introduction to Programming I 156 . It's a placeholder for the void keyword. Primitive types and objects are very different things in Java. so there's no reason it would be used when translating between primitive values and objects. you can create an object that holds the same value. and a program won't compile successfully if you use one when the other is expected. Also.parseInt(pennsylvania). • CAUTION: The Void class represents nothing in Java.3 Converting Primitive Types to Objects and Vice Versa One thing you can't do under any circumstance is cast from an object to a primitive data type. int penn = Integer. The result is an int with //value 7801 int newCount = dataCount. and so on.5. Using the classes that correspond to each primitive type.
J.E.D.I
9.5.4 Comparing Objects
In our previous discussions, we learned about operators for comparing values—equal, not equal, less than, and so on. Most of these operators work only on primitive types, not on objects. If you try to use other values as operands, the Java compiler produces errors. The exceptions to this rule are the operators for equality: == (equal) and != (not equal). When applied to objects, these operators don't do what you might first expect. Instead of checking whether one object has the same value as the other object, they determine whether both sides of the operator refer to the same object. To compare instances of a class and have meaningful results, you must implement special methods in your class and call those methods. A good example of this is the String class. It is possible to have two different String objects that contain the same values. If you were to employ the == operator to compare these objects, however, they would be considered unequal. Although their contents match, they are not the same object. To see whether two String objects have matching values, a method of the class called equals() is used. The method tests each character in the string and returns true if the two strings have the same values. The following code illustrates this, class EqualsTest { public static void main(String[] arguments) { String str1, str2; str1 = "Free the bound periodicals."; str2 = str1; System.out.println("String1: " + str1); System.out.println("String2: " + str2); System.out.println("Same object? " + (str1 == str2)); str2 = new String(str1); System.out.println("String1: " + str1); System.out.println("String2: " + str2); System.out.println("Same object? " + (str1 == str2)); System.out.println("Same value? " + str1.equals(str2));
}
}
This program's output is as follows, OUTPUT: String1: Free the bound String2: Free the bound Same object? true String1: Free the bound String2: Free the bound Same object? false Same value? True periodicals. periodicals. periodicals. periodicals.
Introduction to Programming I
157
J.E.D.I
Now let's discuss the code. String str1, str2; str1 = "Free the bound periodicals.";
Figure 9.5: Both references point to the same object
The first part of this program declares two variables (str1 and str2), assigns the literal "Free the bound periodicals." to str1, and then assigns that value to str2. As you learned earlier, str1 and str2 now point to the same object, and the equality test proves that. str2 = new String(str1); In the second part of this program, you create a new String object with the same value as str1 and assign str2 to that new String object. Now you have two different string objects in str1 and str2, both with the same value. Testing them to see whether they're the same object by using the == operator returns the expected answer: false—they are not the same object in memory. Testing them using the equals() method also returns the expected answer: true—they have the same values.
Figure 9.6: References now point to different objects
NOTE: Why can't you just use another literal when you change str2, rather than using new? String literals are optimized in Java; if you create a string using a literal and then use another literal with the same characters, Java knows enough to give you the first String object back. Both strings are the same objects; you have to go out of your way to create two separate objects.
Introduction to Programming I
158
J.E.D.I
9.5.5 Determining the Class of an Object
Want to find out what an object's class is? Here's the way to do it for an object assigned to the variable key: 1. The getClass() method returns a Class object (where Class is itself a class) that has a method called getName(). In turn, getName() returns a string representing the name of the class. For Example, String name = key.getClass().getName(); 2. The instanceOf operator The instanceOf has two operands: a reference to an object on the left and a class name on the right. The expression returns true or false based on whether the object is an instance of the named class or any of that class's subclasses. For Example, boolean ex1 = "Texas" instanceof String; // true Object pt = new Point(10, 10); boolean ex2 = pt instanceof String; // false
Introduction to Programming I
159
J.E.D.I
9.6 Exercises
9.6.1 Defining terms
In 1. 2. 3. 4. 5. 6. 7. your own words, define the following terms: Class Object Instantiate Instance Variable Instance Method Class Variables or static member variables Constructor
9.6.2 Java Scavenger Hunt
Pipoy is a newbie in the Java programming language. He just heard that there are already ready-to-use APIs in Java that one could use in their programs, and he's eager to try them out. The problem is, Pipoy does not have a copy of the Java Documentation, and he also doesn't have an internet access, so there's no way for him to view the Java APIs. Your task is to help Pipoy look for the APIs (Application Programming Interface). You should state the class where the method belongs, the method declaration and a sample usage of the said method. For example, if Pipoy wants to know the method that converts a String to integer, your answer should be: Class: Integer Method Declaration: public static int parseInt( String value ) Sample Usage: String strValue = "100"; int value = Integer.parseInt( strValue ); Make sure that the snippet of code you write in your sample usage compiles and outputs the correct answer, so as not to confuse Pipoy. (Hint: All methods are in the java.lang package). In cases where you can find more methods that can accomplish the task, give only one. Now let's start the search! 1. Look for a method that checks if a certain String ends with a certain suffix. For example, if the given string is "Hello", the method should return true the suffix given is "lo", and false if the given suffix is "alp". 2. Look for the method that determines the character representation for a specific digit in the specified radix. For example, if the input digit is 15, and the radix is 16, the method would return the character F, since F is the hexadecimal representation for the number 15 (base 10). 3. Look for the method that terminates the currently running Java Virtual Machine 4. Look for the method that gets the floor of a double value. For example, if I input a 3.13, the method should return the value 3. 5. Look for the method that determines if a certain character is a digit. For example, if I input '3', it returns the value true.
Introduction to Programming I
160
J.E.D.I
10 Creating your own Classes
10.1 Objectives
Now that we've studied on how to use existing classes from the Java class library, we will now be studying on how to write our own classes. For this section, in order to easily understand how to create classes, we will make a sample class wherein we will add more data and functionality as we go along the way. We will create a class that contains information of a Student and operations needed for a certain student record. Things to take note of for the syntax defined in this section and for the other sections: * <description> [] - means that there may be 0 or more occurrences of the line whereit was applied to. - indicates that you have to substitute an actual value for this part instead of typing it as it is. - indicates that this part is optional
At the end of the lesson, the student should be able to: • • • • • • Create their own classes Declare attributes and methods for their classes Use the this reference to access instance data Create and call overloaded methods Import and create packages Use access modifiers to control access to class members
Introduction to Programming I
161
J.E.D.I
10.2 Defining your own classes
Before writing your class, think first on where you will be using your class and how your class will be used. Think of an appropriate name for the class, and list all the information or properties that you want your class to contain. Also list down the methods that you will be using for your class. To define a class, we write, <modifier> class <name> { <attributeDeclaration>* <constructorDeclaration>* <methodDeclaration>* }
where <modifier> is an access modifier, which may be combined with other types of modifier. Coding Guidelines: Remember that for a top-level class, the only valid access modifiers are public and package (i.e., if no access modifier prefixes the class keyword). In this section, we will be creating a class that will contain a student record. Since we've already identified the purpose of our class, we can now name it. An appropriate name for our class would be StudentRecord. Now, to define our class we write, public class StudentRecord { //we'll add more code here later } where, public class StudentRecord Coding Guidelines: 1. Think of an appropriate name for your class. Don't just call your class XYZ or any random names you can think of. 2. Class names should start with a CAPITAL letter. 3. The filename of your class should have the SAME NAME as your class name. - means that our class is accessible to other classes outside the package - this is the keyword used to create a class in Java - a unique identifier that describes our class
Introduction to Programming I
162
J.E.D.I
10.3 Declaring Attributes
To declare a certain attribute for our class, we write, <modifier> <type> <name> [= <default_value>]; Now, let us write down the list of attributes that a student record can contain. For each information, also list what data types would be appropriate to use. For example, you don't want to have a data type int for a student's name, or a String for a student's grade. The following are some sample information we want to add to the student record. name address age math grade english grade science grade average grade String String int double double double double
You can add more information if you want to, it's all really up to you. But for this example, we will be using these information.
10.3.1 Instance Variables
Now that we have a list of all the attributes we want to add to our class, let us now add them to our code. Since we want these attributes to be unique for each object (or for each student), we should declare them as instance variables. For example, public class StudentRecord { private String name; private String address; private int age; private double mathGrade; private double englishGrade; private double scienceGrade; private double average; //we'll add more code here later }
where, private here means that the variables are only accessible within the class. Other objects cannot access these variables directly. We will cover more about accessibility later. Coding Guidelines: 1. Declare all your instance variables on the top of the class declaration. 2. Declare one variable for each line. 3. Instance variables, like any other variables should start with a SMALL letter. 4. Use an appropriate data type for each variable you declare. 5. Declare instance variables as private so that only class methods can access them directly.
Introduction to Programming I
163
public class StudentRecord { private String name. } //we'll add more code here later we use the keyword static to indicate that a variable is a static variable.E. private String address. private int age. <modifier> <returnType> <name>(<parameter>*) { <statement>* } where.3.4 Declaring Methods Before we discuss what methods we want our class to have. public class StudentRecord { //instance variables we have declared private static int studentCount. So far. <modifier> can carry a number of different modifiers <returnType> can be any data type (including void) <name> can be any valid identifier <parameter> ::= <parameter_type> <parameter_name>[.I 10. private double englishGrade. private static int studentCount. To declare methods we write. private double average. private double scienceGrade. let us first take a look at the general syntax for declaring methods. } //we'll add more code here later 10. we can also declare class variables or variables that belong to the class as a whole.2 Class Variables or Static Variables Aside from instance variables. Let us call this as studentCount. The value of these variables are the same for all the objects of the same class. our whole code now looks like this. Now suppose. private double mathGrade. To declare a static variable. we want to know the total number of student records we have for the whole class.D.] Introduction to Programming I 164 .J. we can declare one static variable that will hold this value.
Take note that the return type of the method should have the same data type as the data in the return statement. Accessor methods are used to read values from class variables (instance/static). there are times wherein we want other objects to access private data. we don't want any objects to just access our data anytime.is the return type of the method. return name. we want an accessor method that can read the name.J. math grade and science grade of the student.E.D. It also returns a value.String return age. public class StudentRecord { private String name. we create accessor methods. In order to do this. public String getName () The statement. : : public String getName(){ return name.4.this means that our method does not have any parameters where.lang. However. we declare the fields or attributes of our classes as private.1 Accessor methods In order to implement encapsulation. Now let's take a look at one implementation of an accessor method. in our program signifies that it will return the value of the instance variable name to the calling method. english grade.the name of the method . You usually encounter the following error if the two does not have the same data type. For our example. StudentRecord. address.java:14: incompatible types found : int required: java.means that the method can be called from objects outside the class . ^ 1 error Introduction to Programming I 165 . that is. An accessor method usually starts with a get<NameOfInstanceVariable>. } } . This means that the method should return a value of type String .I 10.
} The getAverage method computes the average of the 3 grades and returns the result.D. public class StudentRecord { private String name. what if we want other objects to alter our data? What we do is we provide methods that can write or change values of our class variables (instance/static). assigns the value of temp to name and thus changes the data inside the instance variable name. } } where. public class StudentRecord { private String name. : : public double getAverage(){ double result = 0. name = temp.J. means that the method can be called from objects outside the class imeans that the method does not return any value the name of the method parameter that will be used inside our method Introduction to Programming I 166 . We call these methods. 10. Take note that mutator methods don't return values. mutator methods. : : public void setName( String temp ){ name = temp. public void setName (String temp) The statement. A mutator method is usuallyu written as set<NameOfInstanceVariable>.E.2 Mutator Methods Now. it contains some program argument or arguments that will be used inside the method. However. result = ( mathGrade+englishGrade+scienceGrade )/3.4. Now let's take a look at one implementation of a mutator method. } return result.I Another example of an accessor method is the getAverage method.
Method names should be verbs 3. Coding Guidelines: 1.J. 2. For example. 10.E. Method names should start with a SMALL letter. Please see example. getStudentCount will always return the value zero since we haven't done anything yet in our program in order to set its value. if( num == 1 return } else if( num return } ){ "one".is the return type of the method. we can create a static method to access its value. public String getNumberInWords( int num ){ String defaultNum = "zero".this means that our method does not have any parameters For now. public class StudentRecord { private static int studentCount.[methodName].3 Multiple Return statements You can have multiple return statements for a method as long as they are not on the same block. } } where. [ClassName]. //return a constant } //return a variable return defaultNum.means that the method is static and should be called by typing.the name of the method .means that the method can be called from objects outside the class . public static int getStudentCount () . Introduction to Programming I 167 .4.4.I 10. This means that the method should return a value of type int . You can also use constants to return values instead of variables. we call the method StudentRecord. For example. Always provide documentation before the declaration of the method.D. We will try to change the value of studentCount later on when we discuss constructors. in this case. You can use javadocs style for this.4 Static methods For the static variable studentCount.getStudentCount() . consider the method. public static int getStudentCount(){ return studentCount. //return a constant == 2){ "two".
J. result = ( mathGrade+englishGrade+scienceGrade )/3.4. } /** * Changes the name of the student */ public void setName( String temp ){ name = temp. /** * Computes the average of the english.D. math and science * grades */ public double getAverage(){ double result = 0. average. public class { private private private private private private private StudentRecord String String int double double double double name.E. } Introduction to Programming I 168 .. mathGrade.I 10. scienceGrade. } // other code here . /** * Returns the name of the student */ public String getName(){ return name.. private static int studentCount. } return result.. address. age. englishGrade. } /** * returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount.5 Sample Source Code for StudentRecord class Here is the code for our StudentRecord class.
out.println( annaRecord. crisRecord.getStudentCount } record StudentRecord(). } The output of this program is.setName("Beah"). here's a sample code of a class that uses our StudentRecord class. beahRecord. StudentRecord(). public class StudentRecordExample { public static void main( String[] args ){ //create three objects for Student StudentRecord annaRecord = new StudentRecord beahRecord = new StudentRecord crisRecord = new //set the name of the students annaRecord.println("Count="+StudentRecord. //print anna's name System.E.I Now.setName("Anna"). StudentRecord().out.getName() ).J.D. //print number of students System. ()). Anna Student Count = 0 Introduction to Programming I 169 .setName("Cris").
Since the parameter age is the closest declaration to the method. public void setAge( int age ){ this. public void setAge( int age ){ age = age.D.J. NOTE: You can only use the this reference for instance variables and NOT static or class variables.<nameOfTheInstanceVariable> So for example. } This method will then assign the value of the parameter age to the instance variable of the object StudentRecord. the value of the parameter age will be used.E. So in the statement. To use the this reference. we use the this reference. we are just assigning the value of the parameter age to itself! This is not what we want to happen in our code. let's take for example the setAge method.I 10. age = age. we can now rewrite our code to. we type. Suppose we have the following declaration for setAge.5 The this reference The this reference is used to access the instance variables shadowed by the parameters. which has the same name as the instance variable age. //WRONG!!! } The parameter name in this declaration is age. Introduction to Programming I 170 . this. To understand this better. In order to correct this mistake.age = age.
For example.println("Address:" + address). System. double sGrade) System.6 Overloading Methods In our classes. However. System. For example. we want the print method to print things differently depending on the parameters we pass to it. System. we want the print method to print out the name. address and age of the student. we want the method to print the student's name and grades. public void print( String temp ){ System.println("Math Grade:" + mGrade). System.println("Name:" + name). Method overloading allows a method with the same name but different parameters. System.println("English Grade:" + eGrade).I 10. When we pass 3 double values. method overloading can be used when the same operation has different implementations. in our StudentRecord class we want to have a method that prints information about the student.println("Age:" + age).D. } public void print(double eGrade.out. double mGrade. to have different implementations and return values of different types.out. when we pass a String. We have the following overloaded methods inside our StudentRecord class.println("Science Grade:" + sGrade).out.out.E.out. we want to sometimes create methods that has the same names but function differently depending on the parameters that are passed to them. Rather than invent new names all the time. and it is called Method Overloading. } Introduction to Programming I 171 .out.J. This capability is possible in Java.println("Name:" + name).out.
annaRecord. Name:Anna Address:Philippines Age:15 we will have the output for the second call to print.setAddress("Philippines"). annaRecord. annaRecord.J. annaRecord.print( annaRecord.I When we try to call this in the following main method. } we will have the output for the first call to print. annaRecord.setAge(15).print( annaRecord.getName() ). – the same name – different parameters – return types can be different or the same Introduction to Programming I 172 .5).D.getScienceGrade()).getEnglishGrade(). annaRecord. public static void main( String[] args ) { StudentRecord annaRecord = new StudentRecord(). annaRecord.setMathGrade(80). Name:Anna Math Grade:80.setScienceGrade(100). annaRecord.0 English Grade:95.E.5 Science Grade:100. annaRecord.setEnglishGrade(95.0 Always remember that overloaded methods have the following properties.getMathGrade().setName("Anna"). //overloaded methods annaRecord.
E. for example. Constructors have the same name as the class 2. then an implicit default constructor is created. double sGrade){ mathGrade = mGrade. constructors can also be overloaded.address = address. we have here four overloaded constructors. The default constructor is the constructor without any parameters. A constructor is just like an ordinary method.I 10. Constructors does not have any return value 4. the default constructor would look like this. this. It is a method where all the initializations are placed. Constructors are important in instantiating an object. englishGrade = eGrade.1 Default Constructor Every class has a default constructor. You cannot call a constructor directly. public StudentRecord() { //some code here } 10. } public StudentRecord(double mGrade.7. it can only be called by using the new operator during class instantiation. String address){ this..J. For example.name = name. 3. If the class does not specify any constructors. double eGrade. however only the following information can be placed in the header of the constructor.7.. in our StudentRecord class. we write. public StudentRecord(){ //some initialization code here } public StudentRecord(String temp){ this. constructor's name and parameters if it has any. } public StudentRecord(String name.2 Overloading Constructors As we have mentioned. scienceGrade = sGrade. } Introduction to Programming I 173 . scope or accessibility identifier (like public.D. <modifier> <className> (<parameter>*) { <statement>* } 10.7 Declaring Constructors We have discussed before the concept of constructors. To declare a constructor.name = temp.). The following are the properties of a constructor: 1.
what we want to do here is. studentCount++.name = temp.name = name. public StudentRecord(){ //some initialization code here studentCount++. before we move on.D. So. we have the following code. //add a student } public StudentRecord(String name.I 10.E.7. "Philippines"). //add a student } Introduction to Programming I 174 . double eGrade. The purpose of the studentCount is to count the number of objects that are instantiated with the class StudentRecord. let us go back to the static variable studentCount we have declared a while ago.J. A good location to modify and increment the value of studentCount is in the constructors.3 Using Constructors To use these constructors. public static void main( String[] args ) { //create three objects for Student record StudentRecord annaRecord=new StudentRecord("Anna"). we increment the value of studentCount. englishGrade = eGrade.address = address. scienceGrade = sGrade.90. everytime an object of class StudentRecord is instantiated. StudentRecord StudentRecord (80. studentCount++. studentCount++. For example. crisRecord=new StudentRecord Now. String address){ this. double sGrade){ mathGrade = mGrade. this. //add a student } public StudentRecord(String temp){ this. //add a student } public StudentRecord(double mGrade. because it is always called everytime an object is instantiated.100). //some code here } beahRecord=new StudentRecord("Beah".
meaning. 8: } 9: 10: public static void main( String[] args ) 11: { 12: 13: StudentRecord annaRecord = new StudentRecord(). it will call the default constructor line 1. given the following code. IT MUST OCCUR AS THE FIRST STATEMENT in a constructor 2. When statement in line 2 is executed. 14: } Given the code above. For example. 1: public StudentRecord(){ 2: this("some string"). Introduction to Programming I 175 . you can call another constructor from inside another constructor.7. When using the this constructor call.4 The this() Constructor Call Constructor calls can be chained. when the statement at line 13 is called. 3: 4: } 5: 6: public StudentRecord(String temp){ 7: this.D.J. The this call can then be followed by any other relevant statements. It can ONLY BE USED IN A CONSTRUCTOR DEFINITION.E. it will then call the constructor that has a String parameter (in line 6).name = temp. There are a few things to remember when using the this constructor call: 1. We use the this() call for this.I 10.
The first thing you have to do is create a folder named schoolClasses.*. we write.Color. The first statement imports the specific class Color while the other imports all of the classes in the java. 10. private String address. For example. import java. We will call our package. you have to type the following. public class StudentRecord { private String name. package schoolClasses.2 Creating your own packages To create our own package. import java. : Packages can also be nested. together with other related classes. you need to import the package of those classes.8 Packages Packages are Java’s means of grouping related classes and interfaces together in a single unit (interfaces will be discussed later). the Java interpreter expects the directory structure containing the executable classes to match the package hierarchy. package <packageName>. Introduction to Programming I 176 . In this case.Color color. The syntax for importing packages is as follows.I 10. schoolClasses.* package. all your Java programs import the java.J.1 Importing Packages To be able to use classes outside of the package you are currently working in. This powerful feature provides for a convenient mechanism for managing a large group of classes and interfaces while avoiding potential naming conflicts. that is why you can use classes like String and Integers inside the program eventhough you haven't imported any packages.awt.awt. private int age. if you want to use the class Color inside package awt.E.lang. By default. import <nameOfPackage>. This is done by using the package name to declare an object of a class.8.awt. java. For example.8.D. After copying. Copy all the classes that you want to belong to this package inside this folder. 10. Suppose we want to create a package where we will place our StudentRecord class. Another way to import classes from other packages is through explicit package referencing. add the following code at the top of the class file.awt package.
loadClassInternal(Unknown Source) We encounter a NoClassDefFoundError which means that Java did not know where to look for your class. C:\schoolClasses>javac StudentRecord.net.java C:\schoolClasses>java StudentRecord Exception in thread "main" java.lang. The reason for this is that your class StudentRecord now belongs to a package named studentClasses.findClass(Unknown Source) at java. which in this case is in location C:\. If we want to run our class. Before we discuss how to set the classpath.URLClassLoader.StudentRecord For Unix base systems. C:\schoolClasses> set classpath=C:\ where C:\ is the directory in which we have placed the packages. let us take a look at an example on what will happen if we don't set the classpath. Suppose we compile and then run the StudentRecord class we wrote in the last section.run(Unknown Source) at java.access$100(Unknown Source) at java.lang. we jave to tell Java about its full class name which is schoolClasses.loadClass(Unknown Source) at sun.ClassLoader.net.E.J.defineClass(Unknown Source) at java.Launcher$AppClassLoader.NoClassDefFoundError: StudentRecord (wrong name: schoolClasses/StudentRecord) at java. we write.I 10. suppose we have our classes in the directory /usr/local/myClasses.8. we must set the classpath.defineClass1(Native Method) at java. suppose we place the package schoolClasses under the C:\ directory.net. We also have to tell JVM where to look for our packages.security.lang.loadClass(Unknown Source) at java.ClassLoader.StudentRecord.SecureClassLoader.doPrivileged(Native Method) at java. export classpath=/usr/local/myClasses Introduction to Programming I 177 . We need to set the classpath to point to that directory so that when we try to run it. the JVM will be able to see where our classes are stored.loadClass(Unknown Source) at java.lang.D.misc.net.3 Setting the CLASSPATH Now.AccessController. C:\schoolClasses> java schoolClasses.security.ClassLoader.URLClassLoader. To set the classpath in Windows.ClassLoader. After setting the classpath.URLClassLoader. we type this at the command prompt.defineClass(Unknown Source) at java.URLClassLoader$1.ClassLoader. we can now run our program anywhere by typing.lang.defineClass(Unknown Source) at java. To do this.lang.
E:\MyPrograms\Java and for Unix based systems. For example.I Take note that you can set the classpath anywhere.E. You can also set more than one classpath. set classpath=C:\myClasses.D.J.(for windows) and : (for Unix based systems).D:\. export classpath=/usr/local/java:/usr/myClasses Introduction to Programming I 178 . we just have to separate them by .
For example. For example. 10. we want to implement some kind of restriction to access these data. Any object that interacts with the class can have access to the public members of the class. both inside and outside the class.2 public access This specifies that class members are accessible to anyone.9. as long as the object belongs to the same package where the class StudentRecord belongs to.1 default access (also called package accessibility) This specifies that only classes in the same package can have access to the class' variables and methods. you may want to hide this from other objects using your class. //default access to method String getName(){ return name. no keyword is used. The first three access modifiers are explicitly written in the code to indicate the access type. public class StudentRecord { //default access to instance variable public int name. it is applied in the absence of an access modifier.9 Access Modifiers When creating our classes and defining the properties and methods in our class. } } In this example. In Java. //default access to method public String getName(){ return name. public class StudentRecord { //default access to instance variable int name.9. if you want a certain attribute to be changed only by the methods inside the class.I 10. the instance variable name and the method getName() can be accessed from other objects. private. 10. protected and default.E.D. Introduction to Programming I 179 . There are four different types of member access modifiers in Java: public. for the fourth one which is default.J. For example. the instance variable name and the method getName() can be accessed from other objects. } } In this example. There are no actual keyword for the default modifier. we have what we call access modifiers in order to implement this.
9. and the class will just provide accessor and mutator methods to these variables. the instance variable name and the method getName() can be accessed only from methods inside the class and from subclasses of StudentRecord. 10. } } In this example.9.3 protected access This specifies that the class members are accessible only to methods in that class and the subclasses of the class. //default access to method protected String getName(){ return name. } } In this example. For example. Introduction to Programming I 180 .4 private access This specifies that the class members are only accessible by the class they are defined in. We will discuss about subclasses on the next chapter. the instance variable name and the method getName() can be accessed only from methods inside the class.I 10. //default access to method private String getName(){ return name. Coding Guidelines: The instance variables of a class should normally be declared private. For example.D.E. public class StudentRecord { //default access to instance variable private int name. public class StudentRecord { //default access to instance variable protected int name.J.
10 Exercises 10.1 Address Book Entry Your task is to create a class that contains an address book entry.10. 2. Provide the necessary accessor and mutator methods for all the attributes.J. 4. create the following: 1. Add entry Delete entry View all entries Update an entry Introduction to Programming I 181 . You should provide the following methods for the address book.10.E. 2. The following table describes the information that an adressbook entry has. Constructors 10. 1.D. Attributes/Properties Name Address Telephone Number Email Address Description Name of the person in the addressbook Address of the person Telephone number of the person Person's Email address Table 21: Attributes and Attributes Descriptions For the methods. 3.I 10.2 AddressBook Create a class address book that can contain 100 entries of AddressBookEntry objects (use the class you created in the first exercise).
J.E.D.I
11 Inheritance, Polymorphism and Interfaces
11.1 Objectives
In this section, we will be discussing on how a class can inherit the properties of an existing class. A class that does this is called a subclass and its parent class is called the superclass. We will also be discussing a special property of Java wherein it can automatically apply the proper methods to each object regardless of what subclass the object came from. This property is known as polymorphism. Finally, we are going to discusss about interfaces that helps reduce programming effort. At the end of the lesson, the student should be able to: • • • Define super classes and subclasses Override methods of superclasses Create final methods and final classes
11.2 Inheritance
In Java, all classes, including the classes that make up the Java API, are subclassed from the Object superclass. A sample class hierarchy is shown below. Any class above a specific class in the class hierarchy is known as a superclass. While any class below a specific class in the class hierarchy is known as a subclass of that class.
Inheritance is a major advantage in object-oriented programming since once a behavior (method) is defined in a superclass, that behavior is automatically inherited by all subclasses. Thus, you can encode a method only once and they can be used by all subclasses. A subclass only need to implement the differences between itself and the parent.
Figure 11.1: Class Hierarchy
Introduction to Programming I
182
J.E.D.I
11.2.1 Defining Superclasses and Subclasses
To derive a class, we use the extends keyword. In order to illustrate this, let's create a sample parent class. Suppose we have a parent class called Person. public class Person { protected String protected String
name; address;
/** * Default constructor */ public Person(){ System.out.println(“Inside Person:Constructor”); name = ""; address = ""; } /** * Constructor with 2 parameters */ public Person( String name, String address ){ this.name = name; this.address = address; } /** * Accessor methods */ public String getName(){ return name; } public String getAddress(){ return address; } public void setName( String name ){ this.name = name; } public void setAddress( String add ){ this.address = add; } } Notice that, the attributes name and address are declared as protected. The reason we did this is that, we want these attributes to be accessible by the subclasses of the superclass. If we declare this as private, the subclasses won't be able to use them. Take note that all the properties of a superclass that are declared as public, protected and default can be accessed by its subclasses.
Introduction to Programming I
183
J.E.D.I
Now, we want to create another class named Student. Since a student is also a person, we decide to just extend the class Person, so that we can inherit all the properties and methods of the existing class Person. To do this, we write, public class Student extends Person { public Student(){ System.out.println(“Inside Student:Constructor”); //some code here } } // some code here
When a Student object is instantiated, the default constructor of its superclass is invoked implicitly to do the necessary initializations. After that, the statements inside the subclass are executed. To illustrate this, consider the following code, public static void main( String[] args ){ Student anna = new Student(); } In the code, we create an object of class Student. The output of the program is, Inside Person:Constructor Inside Student:Constructor The program flow is shown below.
Figure 11.2: Program Flow
Introduction to Programming I
184
J.E.D.I
11.2.2 The super keyword
A subclass can also explicitly call a constructor of its immediate superclass. This is done by using the super constructor call. A super constructor call in the constructor of a subclass will result in the execution of relevant constructor from the superclass, based on the arguments passed. For example, given our previous example classes Person and Student, we show an example of a super constructor call. Given the following code for Student, public Student(){ super( "SomeName", "SomeAddress" ); System.out.println("Inside Student:Constructor"); } This code calls the second constructor of its immediate superclass (which is Person) and executes it. Another sample code shown below, public Student(){ super(); System.out.println("Inside Student:Constructor"); } This code calls the default constructor of its immediate superclass (which is Person) and executes it. There are a few things to remember when using the super constructor call: 1. The super() call MUST OCCUR THE FIRST STATEMENT IN A CONSTRUCTOR. 2. The super() call can only be used in a constructor definition. 3. This implies that the this() construct and the super() calls CANNOT BOTH OCCUR IN THE SAME CONSTRUCTOR. Another use of super is to refer to members of the superclass (just like the this reference ). For example, public Student() { super.name = “somename”; super.address = “some address”; }
Introduction to Programming I
185
J.E.D.I
11.2.3 Overriding Methods
If for some reason a derived class needs to have a different implementation of a certain method from that of the superclass, overriding methods could prove to be very useful. A subclass can override a method defined in its superclass by providing a new implementation for that method. Suppose we have the following implementation for the getName method in the Person superclass, public class Person { : : public String getName(){ System.out.println("Parent: getName"); return name; } : } To override, the getName method in the subclass Student, we write, public class Student extends Person { : : public String getName(){ System.out.println("Student: getName"); return name; } : } So, when we invoke the getName method of an object of class Student, the overridden method would be called, and the output would be, Student: getName
Introduction to Programming I
186
J.E.D.I
11.2.4 Final Methods and Final Classes
In Java, it is also possible to declare classes that can no longer be subclassed. These classes are called final classes. To declare a class to be final, we just add the final keyword in the class declaration. For example, if we want the class Person to be declared final, we write, public final class Person { //some code here } Many of the classes in the Java API are declared final to ensure that their behavior cannot be overridden. Examples of these classes are Integer, Double and String. It is also possible in Java to create methods that cannot be overridden. These methods are what we call final methods. To declare a method to be final, we just add the final keyword in the method declaration. For example, if we want the getName method in class Person to be declared final, we write, public final String getName(){ return name; } Static methods are automatically final. This means that you cannot override them.
Introduction to Programming I
187
J.E.D.I
11.3 Polymorphism
Now, given the parent class Person and the subclass Student of our previous example, we add another subclass of Person which is Employee. Below is the class hierarchy for that, Person
Student
Employee
Figure 11.3: Hierarchy for Person class and it's classes
In Java, we can create a reference that is of type superclass to an object of its subclass. For example, public static main( String[] args ) { Person ref; Student Employee studentObject = new Student(); employeeObject = new Employee();
ref = studentObject; //Person ref points to a // Student object } //some code here
Now suppose we have a getName method in our superclass Person, and we override this method in both the subclasses Student and Employee, public class Person { public String getName(){ System.out.println(“Person Name:” + name); return name; } } public class Student extends Person { public String getName(){ System.out.println(“Student Name:” + name); return name; } } public class Employee extends Person { public String getName(){ System.out.println(“Employee Name:” + name); return name; } }
Introduction to Programming I
188
while automatically selecting the proper methods to apply to a particular object based on the subclass it belongs to. Student Employee studentObject = new Student(). } Introduction to Programming I 189 . Employee employeeObject = new Employee().out.println( temp ). printInformation( studentObject ).E. . } This ability of our reference to change behavior according to what object it is holding is called polymorphism. . ref = employeeObject.D. Another example that exhibits the property of polymorphism is when we try to pass a reference to methods. if we assign ref to an Employee object. the getName method of the Student object will be called. ref = studentObject. Suppose we have a static method printInformation that takes in a Person object as reference.out. public static printInformation( Person p ){ . } printInformation( employeeObject ). employeeObject = new Employee(). //getName of Student //class is called System. the getName method of Employee will be called. //getName of Employee //class is called System. Polymorphism allows multiple objects of different subclasses to be treated as objects of a single superclass. . when we try to call the getName method of the reference Person ref.I Going back to our main method. //Person reference points to an // Employee object String temp = ref.println( temp ). public static main( String[] args ) { Person ref. public static main( String[] args ) { Student studentObject = new Student().getName(). //Person reference points to a // Student object String temp = ref.J. Now. we can actually pass a reference of type Employee and type Student to this method as long as it is a subclass of the class Person.getName().
This class has certain methods like breath. we want to create a superclass named LivingThing. just write the method declaration without the body and use the abstract keyword. there are many characteristics that living things have in common. Take the humans for instance. we humans walk on two legs. It often appears at the top of an object-oriented programming class hierarchy. and some methods wherein we just want to be overridden by its subclasses. we can create a superclass that has some methods with implementations and others which do not. However. sleep and walk.E. For example. the walk method. An abstract class is a class that cannot be instantiated. This kind of class is called an abstract class. Those methods in the abstract classes that do not have implementation are called abstract methods. eat.J. while other living things like dogs walk on four legs. that is why we want to create a general superclass for this. Take for example. there are some methods in this superclass wherein we cannot generalize the behavior. However. Introduction to Programming I 190 .4: Abstract class In order to do this. defining the broad types of actions possible with objects of all subclasses of the class.I 11. For example. Figure 11. Not all living things walk the same way.D. To create an abstract method. public abstract void someMethod().4 Abstract Classes Now suppose we want to create a superclass wherein it has certain methods in it that contains some implementation.
println("Human walks..out.").I Now. and use its subclasses to provide implementation details of the abstract class. or else.println("Living Thing breathing. } /** * abstract method walk * We want this method to be overridden by subclasses of * LivingThing */ public abstract void walk(). } } If the class Human does not override the walk method. let's create an example abstract class.").D. Human.. } When a class extends the LivingThing abstract class.java:1: Human is not abstract and does not override abstract method walk() in LivingThing public class Human extends LivingThing ^ 1 error Coding Guidelines: Use abstract classes to define broad types of behaviors at the top of an object-oriented programming class hierarchy.println("Living Thing eating. it is required to override the abstract method walk().out.out.. we would encounter the following error message.E. and therefore cannot be instantiated. For example. public class Human extends LivingThing { public void walk(){ System.")..J.. public abstract class LivingThing { public void breath(){ System. } public void eat(){ System.. Introduction to Programming I 191 . that subclass will also become an abstract class.
11. Introduction to Programming I 192 . Object b). public interface Relation { public boolean isGreater( Object a.5 Interfaces An interface is a special kind of block containing method signatures (and possibly constants) only. Our interface Relation can be declared as.D. Classes. let's say interface Relation which has some comparison method declarations. suppose we have another class MyInteger which contains methods that compares a MyInteger object to objects of the same class. } Another reason for using an object's programming interface is to reveal an object's programming interface without revealing its class.5. In order to enforce a way to make sure that these two classes implement some methods with similar signatures. As we can see later on the section Interface vs. but present in other object-oriented languages like C++.J. Interfaces define a standard and public way of specifying the behavior of classes. Object b).I 11. As we can see here. we need to use interfaces to model multiple inheritance which allows a class to have more than one superclass. public boolean isEqual( Object a. Object b). 11. Finally. an interface can only define constants and an interface have no direct inherited relationship with any particular class.2 Interface vs. but they are not related whatsoever. public boolean isLess( Object a. Let's take as an example a class Line which contains methods that computes the length of the line and compares a Line object to objects of the same class. we can actually capture similarities among unrelated classes without artificially forcing a class relationship. Interfaces define the signatures of a set of methods without the body. both of the classes have some similar methods which compares them from other objects of the same type. they are defined independently. Multiple inheritance is not present in Java. regardless of their location in the class hierarchy. They allow classes. Abstract Class The following are the main differences between an interface and an abstract class: interface methods have no body. We can create an interface class. we can use an interface for this.5.E. to implement common behaviors. we can actually use an interface as data type. Thru interfaces. Now. since program may call an interface method and the proper version of that method will be executed depending on the type of object passed to the interface method call. Note that interfaces exhibit polymorphism as well.1 Why do we use Interfaces? We need to use interfaces if we want unrelated classes to implement similar methods.
However. public boolean isLess( Object a. For example. public interface [InterfaceName] { //some methods without the body } As an example. Class One common characteristic of an interface and class is that they are both types. we write. private double y1. Object b). However. this.y1 = y1. An example of this is: PersonInterface pi = new PersonInterface().J.3 Interface vs. 11.4 Creating Interfaces To create an interface. this. private double x2. you cannot create an instance from an interface. /** * This class defines a line segment */ public class Line implements Relation { private double x1. given a class Person and an interface PersonInterface. this.y2 = y2. double y2){ this. let's create an interface that defines relationships between two objects according to the “natural order” of the objects. public boolean isEqual( Object a. This means that an interface can be used in places where a class can be used. private double y2. the following declarations are valid: PersonInterface Person pi = new Person(). Object b). } public double getLength(){ Introduction to Programming I 193 .x1 = x1. double x2. we use the implements keyword. Object b). double y1. public Line(double x1.5.I 11.E. //COMPILE //ERROR!!! Another common characteristic is that both interface and class can define methods.D.x2 = x2. to use the interface. an interface does not have an implementation code while the class have one. public interface Relation { public boolean isGreater( Object a.5. } Now. For example. pc = new Person().
getLength(). return (aLen == bLen). Object b){ double aLen = ((Line)a). public boolean isGreater( Object a.sqrt((x2-x1)*(x2-x1) + (y2-y1)* (y2-y1)). or else.lang.getLength().Object) in Relation public class Line implements Relation ^ 1 error Coding Guidelines: Use interfaces to create the same standard method definitions in may different classes.getLength(). double bLen = ((Line)b). Introduction to Programming I 194 .java.java:4: Line is not abstract and does not override abstract method isGreater(java.getLength(). double bLen = ((Line)b). Object b){ double aLen = ((Line)a). you would encounter this error. always make sure that you implement all the methods of that interface. } public boolean isLess( Object a.J.E. Once a set of standard method definition is created. double bLen = ((Line)b). return (aLen > bLen).D.getLength().lang. } } When your class tries to implement an interface. Object b){ double aLen = ((Line)a).getLength().Object. return (aLen < bLen). Line. you can write a single method to manipulate all of the classes that implement the interface. return length. } public boolean isEqual( Object a.I } double length = Math.
5. An example of a class that implements many interfaces is. Unrelated classes can implement the same interface. LivingThing. If StudentInterface extends PersonInterface. Another thing to note about the relationship of interfaces to classes is that. 11.I 11. .6 Inheritance among Interfaces Interfaces are not part of the class hierarchy. suppose we have two interfaces StudentInterface and PersonInterface. but it can IMPLEMENT MANY interfaces.5 Relationship of an Interface to a Class As we have seen in the previous section. . interfaces can have inheritance relationship among themselves. public class ComputerScienceStudent extends Student implements PersonInterface. } public interface StudentInterface extends PersonInterface { .5.J. it will inherit all of the method declarations in PersonInterface. a class can only EXTEND ONE super class. . . a class can implement an interface as long as it provides the implementation code for all the methods defined in the interface. WhateverInterface { } //some code here Another example of a class that extends one super class and implements an interface is. LivingThing { } //some code here Take note that an interface is not part of the class inheritance hierarchy. public interface PersonInterface { . public class Person implements PersonInterface.D.E. } Introduction to Programming I 195 . However. For example.
Add some attributes and methods that you think are needed for a Computer Science student record. Write two of its subclasses Circle and Square. if you really need to.6. 11. we want to create a more specialized student record that contains additional information about a Computer Science student. Try to override some existing methods in the superclass StudentRecord.6.I 11.E. Your task is to extend the StudentRecord class that was implemented in the previous lessons.1 Extending StudentRecord In this exercise.6 Exercises 11.2 The Shape abstract class Try to create an abstract class called Shape with abstract methods getArea() and getName(). You can add additional methods to its subclasses if you want to.J. Introduction to Programming I 196 .D.
This technique is called exception handling. 12.I 12 Basic Exception Handling 12. .parseInt method. or maybe a NumberFormatException.1 Objectives In this section. The general form of a try-catch-finally block is. At the end of the lesson. What we do in our programs is that we place the statements that can possibly generate an exception inside this block.D. which occurs if we try to access a non-existent array element. try{ //write the statements that can generate an exception //in this block } catch( <exceptionType1> <varName1> ){ } . we use a try-catch-finally block.3 Handling Exceptions To handle exceptions in Java. Some examples of exceptions that you might have encountered in our previous exercises are: ArrayIndexOutOfBounds exceptions. This event is usually some error of some sort. the student should be able to: • • Define exceptions Handle exceptions using a simple try-catch-finally block 12. catch( <exceptionTypen> <varNamen> ){ //write the action your program will do if an //exception of a certain type occurs } finally{ //add more cleanup code here } //write the action your program will do if an exception //of a certain type occurs Introduction to Programming I 197 .J. we are going to study a technique used in Java to handle unusual conditions that interrupt the normal operation of the program.E. This causes our program to terminate abnormally. which occurs when we try to pass as a parameter a non-number in the Integer. .2 What are Exceptions? An exception is an event that interrupts the normal processing flow of a program.
main(ExceptionExample. and in the above order. but only one finally block.E.java:5) Introduction to Programming I 198 .lang. • A try block must be followed by at least one catch block OR one finally block. we'll get the following exception. The following are the key aspects about the syntax of the try-catch-finally construct: • The block notation is mandatory. there is no checking inside your code for the number of arguments and we just access the second argument args[1] right away. which is the exception its block is willing to handle. The header of the catch block takes exactly one argument. Figure 12. • Each catch block defines an exception handle.ArrayIndexOutOfBoundsException: 1 at ExceptionExample. Suppose.D. The exception must be of the Throwable class or one of its subclasses. • The catch blocks and finally blocks must always appear in conjunction with the try block. or both.J.I Exceptions thrown during execution of the try block can be caught and handled in a catch block. Exception in thread "main" java. The code in the finally block is always executed.1: Flow of events in a try-catch-finally block Let's take for example a code that prints the second argument when we try to run the code using command-line arguments. there can be one or more catch blocks. • For each try block.
println( args[1] ). Exception caught! Introduction to Programming I 199 . we won't use the finally block.println("Exception caught!"). }catch( ArrayIndexOutOfBoundsException exp ){ System. } } try{ } So when we try to run the program again without arguments.D. The finally block is just optional.E.out. the output would be.I To prevent this from happening.J. we can place the code inside a try-catch block. For this example. public class ExceptionExample { public static void main( String[] args ){ System.out.
ArrayIndexOutOfBoundsException: 3 at TestExceptions.4.E. Go back to those programs and implement exception handling. } } } Compile and run the TestExceptions program. 12.4.main(1. i++ ){ System. The output of the program after catching the exception should look like this: javac TestExceptions one two three args[0]=one args[1]=two args[2]=three Exception caught: java. The output should look like this: javac TestExceptions one two three args[0]=one args[1]=two args[2]=three Exception in thread "main" java.out.J. Introduction to Programming I 200 .println("args["+i+"]="+ args[i]).I 12.lang..2 Catching Exceptions 2 Chances are very good that some programs you've written before have encountered exceptions.4 Exercises 12.D. Since you didn't catch the exceptions.1 Catching Exceptions1 Given the following code: public class TestExceptions{ public static void main( String[] args ){ for( int i=0.lang. true. they simply halted the execution of your code.ArrayIndexOutOfBoundsException: 3 Quiting.java:4) Modify the TestExceptions program to handle the exception..
For Windows: Just copy the installers in any temporary directory.5.com/j2se/1.I Appendix A : Java and Netbeans Installation In this section.D. Introduction to Programming I 201 . copy the installers in your hard disk first.E. For Linux: Create a folder under the /usr directory and name it java.0 installers by your instructor. we will discuss on how to install Java and Netbeans in your system (Redhat Linux 9. you can download a copy of the installers from the Sun Microsystems website (http://java. If you are not provided with the Java 1.0/Windows XP). Before starting with the installation.0/download.org/downloads/ for Netbeans). You will now have a /usr/java directory. and copy all the installers inside this folder.J.jsp for Java and http://www.5 and Netbeans 4.sun.netbeans.
E.2: Start Terminal Introduction to Programming I 202 .I Installing Java in Linux Step 1: Run Terminal To start Terminal. click on Menu-> System Tools-> Terminal Figure 12.D.J.
D.I Step 2: Go to the folder where you copied the Java installer. type: cd /usr/java Figure 12.J.3: Change directory Introduction to Programming I 203 . To go to the folder.E.
Figure 12.I To make sure that all installers you need are already in the folder. To do this.4: List all files Make your installer file executable by using the chmod command. type: chmod u+x jdk-1_5_0_01-linux-i586.E.bin Figure 12.5: Make an installer an executable file Introduction to Programming I 204 .D. type: ls The ls (list) command will list all the files inside your directory.J.
J.E.D.I Step 3: Run the installer To run the installer. just type: .6: Run installer Introduction to Programming I 205 .bin Figure 12./jdk-1_5_0_01-linux-i586.
D.E. and press ENTER.I After pressing ENTER.8: License agreement Introduction to Programming I 206 . Figure 12. Just type: yes.9: License agreement Figure 12.7: License agreement Figure 12. until you see the question: Do you agree to the above license terms? [yes or no]. Just press enter. you will see the license agreement displayed on the console.J.
J.E.D.I Just wait for the installer to finish unpacking all its contents and installing java.10: Finish installation Introduction to Programming I 207 . Figure 12.
To do this.E. go to the directory:/usr/local/bin. we need to create symbolic links for all the commands in JDK inside the /usr/local/bin directory.J.I Step 4: Creating symbolic links In order to run java commands anywhere. Type: cd /usr/local/bin Figure 12.D.11: Change directory Introduction to Programming I 208 .
E.D.J.0_01/bin/* . type: ln -s /usr/java/jdk1. Figure 12.5.12: Create Symbolic links Introduction to Programming I 209 .I To make the symbolic links to the commands.
D.13: Folder containing installers Introduction to Programming I 210 . go to the folder where your Java installer is located Figure 12.E.J.I Installing Java in Windows Step 1: Using Windows Explorer.
J.E.D.14: License agreement Introduction to Programming I 211 . A J2SE installer dialog will then appear.I Step 2: Run the installer To run the installer. Click on the radio button labeled "I accept the terms in the license agreement" and press NEXT. just double-click on the installer icon. Figure 12.
15: Custom setup Click on FINISH to complete installation.D.I Click on NEXT to continue installation.16: Finish installation Introduction to Programming I 212 . Figure 12.E. Figure 12.J.
17: Run Console Introduction to Programming I 213 .J.D. click on Menu-> System Tools-> Terminal Figure 12.I Installing Netbeans in Linux Step 1: Run Terminal To start Terminal.E.
18: Change directory Introduction to Programming I 214 .E. type: cd /usr/java Figure 12.J.I Step 2: Go to the folder where you copied the Netbeans installer.D. To go to the folder.
Figure 12.bin Figure 12.I To make sure that all installers you need are already in the folder. To do this.J.E.D. type: chmod u+x netbeans-4_0-bin-linux.20: Make installer an executable Introduction to Programming I 215 .19: List all files Make your installer file executable by using the chmod command. type: ls The ls (list) command will list all the files inside your directory.
E. Click on NEXT.21: Run installer Figure Introduction to Programming I 12.I Step 3: Run Installer To run the netbeans installer.22: Netbeans installation wizard 216 . Figure 12. type: .0 Installer dialog will then appear./netbeans-4_0-bin-linux.D.bin A netbeans 4.J.
For the directory name.E. And then click on NEXT.J. Figure 12. then click on NEXT.23: Netbeans license agreement Figure 12.D. change it to: /usr/java/netbeans-4.I Click on the radio button that says "I accept the terms in the license agreement".0.24: Choose directory on where to install netbeans Introduction to Programming I 217 .
26: Installation summary Introduction to Programming I 218 .E. Just click again on NEXT.I For the JDK directory. The next dialog just shows information about Netbeans thatyou will install.D. Figure 12. choose /usr/java/jdk1.5.J.25: Choose jdk version to use Figure 12.0_01. and then click on NEXT.
D.28: Installation successful Introduction to Programming I 219 .J.E. Figure 12. just wait for netbeans to finish its installation.I Now. Figure 12.27: Netbeans installation Click on FINISH to complete the installation.
J. Type: cd /usr/local/bin Make a symbolic link to the netbeans executable by typing: ln -s /usr/java/netbeans-4. go first to the directory:/usr/local/bin.0/bin/netbeans .D. we need to create symbolic link for it. To do this.30: Create symbolic links Introduction to Programming I 220 .E.I Step 4: Creating symbolic links In order to run netbeans anywhere.29: Change directory Figure 12. Figure 12.
you can run netbeans in any directory by typing: netbeans & Figure 12.D.I Now.31: Netbeans running Introduction to Programming I 221 .E.J.
just double-click on the installer icon.32: Netbeans installer files Step 2: Run the installer To run the installer. Figure 12.D. go to the folder where your Netbeans installer is located Figure 12. Click on NEXT to enter installation process.E. the Netbeans installation wizard will appear.J.33: Netbeans installation Introduction to Programming I 222 . After clicking on the netbeans4_0-bin-windows icon.I Installing Netbeans in Windows Step 1: Using Windows Explorer.
J. Choose to ACCEPT and click NEXT to continue. You can move on by clicking NEXT or you can click on BROWSE to choose a different directory.34: License agreement Figure 12. Then you will be given the choice on which directory to place the Netbeans.I The agreement page will the appear.D. Figure 12.35: Choose directory where to install Netbeans Introduction to Programming I 223 .E.
I Next is choosing the Standard Edition JDKs from your machine.37: Installation summary Introduction to Programming I 224 . Figure 12. If you have finished installing Java.J.5.E. It will then inform you the location and size of Netbeans which will be installed to your machine.D. the jdk1. Click on NEXT to finish installation.0_01 chould appear from your choices.36: Choose JDK to use Figure 12. Click on NEXT to continue.
Figure 12.J.D.38: Successful installation Introduction to Programming I 225 .E. Click on FINISH to complete installation.I You have installed Netbeans on your computer.
My First Java Program public class Hello { /** * My first java program */ public static void main(String[] args) { //prints the string "Hello world" on screen System. Before going into details.E. the first one is by using a console and a text editor. The second one is by using Netbeans which is an Integrated Development Environment or IDE. let us first take a look at the first Java program you will be writing. Introduction to Programming I 226 . let's first try to write this program in a file and try to run it.println("Hello world!"). There are two ways of doing this.D.out. a compiler and/or interpreter and a debugger. compile and run Java programs.J. we will be discussing on how to write. a text or code editor. } } Before we try to explain what the program means. An IDE is a programming environment integrated into a software application that provides a GUI builder.I Appendix B: Getting to know your Programming Environment (Windows XP version) In this section.
we will be using the text editor "Notepad"(for Windows) to edit the Java source code.J. Step 1: Start Notepad To start Notepad in Windows.I Using a Text Editor and Console For this example. click on start-> All Programs-> Accessories-> Notepad. You can use other text editors if you want to.D. Figure 12.40: Notepad Application Figure 12.E.39: Click on start-> All Programs-> Accessories -> Notepad Introduction to Programming I 227 . You will also need to open the MS-DOS prompt window to compile and execute your Java programs.
41: start-> All programs-> Accessories -> Command Prompt Figure 12.I Step 2: Open the Command Prompt window To open the MSDOS command prompt in Windows. click on start-> All programs-> Accessories-> Command Prompt. Figure 12.42: MSDOS Command Prompt Introduction to Programming I 228 .J.D.E.
E. and we will be saving it inside a folder named MYJAVAPROGRAMS.java". Introduction to Programming I 229 .J.I Step 3: Write your the source code of your Java program in Notepad Step 4: Save your Java Program We will save our program on a file named "Hello. click on the File menu found on the menubar and then click on Save. To open the Save dialog box.D.
Introduction to Programming I 230 .43: This Dialog appears after clicking on File -> Save Click on the MY DOCUMENTS button to open the My Documents folder where we will be saving all your Java programs. Figure 12.I After doing the procedure described above.D.E.J. a dialog box will appear as shown in Figure below.
45: Clicking on the encircled button will create a New Folder. This will open your "My Documents" folder Figure 12.D. Figure 12.44: Click on the button encircled. we'll create a new folder inside the My Documents folder where we will save your programs.E.I Now. Click on the button encircled in the figure below to create the folder. We shall name this folder MYJAVAPROGRAMS.J. Introduction to Programming I 231 .
In this case.E. type in MYJAVAPROGRAMS. Introduction to Programming I 232 .I After the folder is created.J. and then press ENTER. you can type in the desired name for this folder.D.
double click on that folder to open it.E. You will see a similar figure as shown below. Introduction to Programming I 233 .D.J. The folder should be empty for now since it's a newly created folder and we haven't saved anything in it yet.I Now that we've created the folder where we will save all the files.
in the Filename textbox. Click on the "All Files" option. Now.I Now click on the drop down list box "Save as type". type in the filename of your program. and then click on the SAVE button.D. which is "Hello. Introduction to Programming I 234 .J.java".E. so that we can choose what kind of file we want to save.
you can just edit it. Take note that if you want to make changes in your file. notice how the title of the frame changes from UntitledNotepad to Hello. and then save it again by clicking on File -> Save. Introduction to Programming I 235 .java-Notepad.E.J.D.I Now that you've saved your file.
the next step is to compile your program. Figure 12.J. Introduction to Programming I 236 .D. To see what is inside that home folder. Now.I Step 5: Compiling your program Now.46: List of files and folders shown after executing the command DIR. when you open the command prompt window. type DIR or dir and then press ENTER. you can see here that there is a folder named "My Documents" where we created your MYJAVAPROGRAMS folder. it opens up and takes you directly to what is called your home folder.E. What you will see is a list of files and folders inside your home folder. Typically. Go to the MSDOS command prompt window we just opened a while ago. Now let's go inside that directory.
try typing in the "dir" command again. and tell me what you see. you type in the command: cd [directory name].I To go inside a directory. since the name of our directory is My Documents. Figure 12. change directory. Introduction to Programming I 237 . Figure 12.E.D. In this case.J.47: Inside the My Documents folder Now that you are inside the "My Documents" folder. you type in: cd My Documents.48: The contents of My Documents Now perform the same steps described before to go inside the MYJAVAPROGRAMS folder. The "cd" command stands for.
So in this case. Introduction to Programming I 238 . Figure 12. javac adds a file to the disk called [filename].class. type in: javac Hello. Hello.49: Inside the MYJAVAPROGRAMS folder Figure 12. or in this case.J.java. To compile a Java program. In order to do that.D. you should make sure that the file is inside the folder where you are in.E. we type in the command: javac [filename].I Once inside the folder where your Java programs are.class. which is the actual bytecode. Take note that. let us now start compiling your Java program. execute the dir command again to see if your file is inside that folder.50: Compile program by usingthe javac command During compilation.
J. "Hello world!". we are now ready to run your program. To run your Java program. Figure 12.I Step 6: Running the Program Now.D.51: Output of the program Introduction to Programming I 239 .E. so in the case of our example. assuming that there are no problems during compilation (we'll explore more of the problems encountered during compilation in the next section). type in the command: java [filename without the extension]. type in: java Hello You can see on the screen that you have just run your first Java program that prints the message.
operable program or batch file. This means that either you haven't installed Java in your system yet. you can now use the Java commands. try setting the PATH variable to point to where the Java commands are installed. you encounter the message: 'javac' is not recognized as an internal or external command.E.53: Setting the path and running java Introduction to Programming I 240 . This will tell your system to look for the commands in the C:\j2sdk1. Figure 12. Figure 12.4.52: System did not recognize the javac command If you are sure that you've already installed Java in your system. After doing this. To do this. which is usually the default location wherein your Java files are placed during installation.I Setting the Path Sometimes.J. or you have to configure the path on where the Java commands are installed so that your system will know where to find them.D.4.2_04\bin folder.2_04\bin. type in the command: set PATH=C:\j2sdk1. when you try to invoke the javac or java command.
let's now see how to do all the processes we've described in the previous sections by using just one application. click on start-> All Programs-> NetBeans 4. Step 1: Run Netbeans To run Netbeans.0 -> NetBeans IDE Introduction to Programming I 241 . An IDE is a programming environment integrated into a software application that provides a GUI builder.E. which is an Integrated Development Environment or IDE.I Using Netbeans Now that we've tried doing our programs the complicated way. a text or code editor. we will be using Netbeans.D.J. In this part of the lesson. a compiler and/or interpreter and a debugger.
D.E.54: NetBeans IDE Introduction to Programming I 242 .I After you've open NetBeans IDE. Figure 12. you will see a graphical user interface (GUI) similar to what is shown below.J.
let's first make a project. Click on File-> New Project.D. a New Project dialog will appear. Introduction to Programming I 243 .J.E.I Step 2: Make a project Now. After doing this.
J. Introduction to Programming I 244 .I Now click on Java Application and click on the NEXT button. Edit the Project Name part and type in "HelloApplication". a New Application dialog will appear.E.D. Now.
J. on the Create Main Class textfield. and then click on the FINISH button.E. Follow the steps described in the previous section to go to your MYJAVAPROGRAMS folder. type in Hello as the main class' name.D. Finally. Introduction to Programming I 245 .I Figure 12.55: Change Project Name Now try to change the Application Location. by clicking on the BROWSE button.
J. Introduction to Programming I 246 .D. let us first describe the main window after creating the project. NetBeans automatically creates the basic code for your Java program. As shown below. where you set the Project location. You can just add your own statements to the generated code. On the left side of the window.E.I Step 3: Type in your program Before typing in your program. you can see a list of folders and files that NetBeans generated after creating the project. This can all be found in your MYJAVAPROGRAMS folder.
you could also use the shortcut button to compile your code. Or.J. just click on Build -> Build Main Project. Introduction to Programming I 247 . after the statement. to compile your program.println("Hello world!").E.out.I Now. try to modify the code generated by Netbeans. as we will explain the details of the code later. Insert the code: System. Step 4: Compile your program Now. Ignore the other parts of the program for now. //TODO code application logic here.D.
D.J.E.I Figure 12.56: Shortcut button to compile code Introduction to Programming I 248 .
E.D. Figure 12. you will see a build successful message on the output window.57: Output window just below the window where you type your source code Introduction to Programming I 249 .J.I If there are no errors in your program.
Or you could also use the shortcut button to run your program. Figure 12.J.E. click on Run-> Run Main Project. Figure 12.59: Output of Hello.I Step 5: Run your program To run your program.D.java Introduction to Programming I 250 .58: Shortcut button to run program The output of your program is displayed in the output window.
Baking Bread Pseudocode: prepare all ingredients pour all ingredients in mixing bowl while batter not smooth yet mix ingredients pour into bread pan place inside oven while bread not yet done wait Flowchart: remove from oven Introduction to Programming I 251 .D.1 Writing Algorithms 1.J.E.I Appendix C : Answers to Exercises Chapter 1 Exercises 1.
J.E.D.I 2. Logging into your laboratory's computer Pseudocode: Let power = computer's power button Let in = status of user (initially false) if power == off Press power button Enter "boot" process while in== false enter user name enter password if password and user name correct in = true end while Flowchart: Introduction to Programming I 252 .
J. Getting the average of three numbers Pseudocode: Let count = 0 Let sum = 0 Let average = 0 While count < 3 Get number sum = sum + number count++ average = sum/3 Flowchart: Display average Introduction to Programming I 253 .I 3.D.E.
hexadecimal and octal To Binary: 1980/2 = 990 990/2 = 495 495/2 = 247 247/2 = 123 123/2 = 61 61/2 = 30 30/2 = 15 15/2 = 7 7/2 = 3 3/2 = 1 1/2 = 0 Binary = 11110111100 To Hexadecimal: 0111. 3 Octal = 3674 110. B 1100. 198010 to binary. 7 100 4 Introduction to Programming I 254 .D. 6 111.2 Number Conversions 1.I 1. C 0 0 1 1 1 1 0 1 1 1 1 011.J.E. 7 Hexadecimal = 7BC To Octal: 1011.
D. 10010011012 to decimal. 1 Octal = 1115 001.E. 2 Hexadecimal = 24D To Octal: 0100. 1 101 5 Introduction to Programming I 255 .J.I 2. 4 1101 D 001. hexadecimal and octal To Decimal: 1*1 = 1 0*2 = 0 1*4 = 4 1*8 = 8 0 * 16 = 0 0 * 32 = 0 1 * 64 = 64 0 * 128 = 0 0 * 256 = 0 1 * 512 = 512 TOTAL= 589 Decimal = 589 To Hexadecimal: 0010. 1 001.
J.I 3. 3 Hexadecimal = 3E To Decimal: 6*1= 6 7 * 8 = 56 TOTAL = 62 Decimal = 62 1110. 7 Binary = 111110 To Hexadecimal: 110. 6 0011. 768 to binary.E. hexadecimal and decimal To Binary: 111.D. E Introduction to Programming I 256 .
43F16 to binary. Binary = 010000111111 To Decimal: F * 1 = 15 3 * 16 = 48 4 * 256 = 1024 TOTAL= 1087 Decimal = 1087 To Octal: 3 0011.D.E. 7 111 7 Chapter 2 (No exercises) Introduction to Programming I 257 . F 1111 010. 2 Octal = 02077 000 .J. 0 111 .I 4. decimal and octal To Binary: 4 0100.
println("A tree whose hungry mouth is pressed").println("I think I shall never see.").println("a poem as lovely as a tree.out.println("Against the Earth's flowing breast.out.out.J."). System.E.").println("Welcome to Java Programming [YourName]!!!"). } } 3.1 Hello World! /** * This class prints the line "Welcome to Java Programming [YourName]!!!" * on screen.I Chapter 3 Exercises 3. System. */ public class HelloWorld { public static void main(String[] args){ System.out.D. System.out. } } Introduction to Programming I 258 .2 The Tree /** * A program that prints four lines on screen */ public class TheTree { public static void main(String[] args){ System.
2 Getting the average of three numbers /** * A program that solves for the average * of the three numbers: 10.out. System. 45.20.I Chapter 4 Exercises 4. //prints the output on the screen System.out.out.out. } } 4.out.println("Number = "+number).println("str = "+str). 20.out.out.E.J. System.println("Average is = "+ave). //declares character letter with 'a' as initial value char letter = 'a'. System.D. System.println("number 2 = "+num2). and 45 * then outputs the result on the screen */ public class AverageNumber { public static void main(String[] args){ //declares int num1 = int num2 = int num3 = the three numbers 10. System.1 Declaring and printing variables /** * A program that declares different variables * then outputs the values of the variables */ public class VariableSample { public static void main(String[] args){ //declares integer number with 10 as initial value int number = 10. //get the average of the three numbers // and saves it inside the ave variable int ave = (num1+num2+num3)/3. //declares String str with "hello" as initial value String str = "hello". //prints the values of the variables on screen System.println("number 3 = "+num3). System.println("result = "+result).println("number 1 = "+num1). //declares boolean result with true as initial value boolean result = true.println("letter = "+letter). } } Introduction to Programming I 259 .out.
out.println("The highest number is = "+max).3 Output greatest value /** * A program that outputs the number with * the greatest value given thre numbers */ public class GreatestValue { public static void main(String[] args){ //declares the numbers int num1 = 10.println("number 2 = "+num2).out. System. //determines the highest number max = (num1>num2)?num1:num2. (((a/b)^c)^((d-e+f-(g*h))+i)) 2.out.D. //prints the output on the screen System.I 4.out.E. int max = 0. ((((((3*10)*2)/15)-2+4)^2)^2) 3.4 Operator precedence 1. System.println("number 1 = "+num1). ((r^((((s*t)/u)-v)+w))^(x-(y++))) Introduction to Programming I 260 .println("number 3 = "+num3). System. } } 4. max = (max>num3)?max:num3. int num3 = 5.J. int num2 = 23.
thirdWord = reader.readLine().in)).println(firstWord + " " + secondWord + " " + thirdWord).I Chapter 5 Exercises 5. try{ System. secondWord = reader.E. } //prints the phrase System. String secondWord = "".out.//gets the 2nd word System.out.io. firstWord = reader.*.//gets the 3rd word }catch( IOException e){ System.print("Enter word1: ").print("Enter word3: ").println("Error in getting input").J.readLine().1 Last 3 words (BufferedReader version) import java. String thirdWord = "".out.//gets the 1st word System. //declares the String variables for the three words String firstWord = "". /** * A program that asks three words from the user * and then prints it on the screen as a phrase */ public class LastThreeWords { public static void main(String[] args){ //declares the variable reader as the BufferedReader reader = new BufferedReader( new InputStreamReader( System.print("Enter word2: ").out. } } Introduction to Programming I 261 .D.out.readLine().
swing.D. //displays the message JoptionPane.showMessageDialog(null. //gets the second word from the user String secondWord = JoptionPane.firstWord+ " "+secondWord+ " "+thirdWord).I 5.showInputDialog ("Enter word1").JOptionPane.showInputDialog ("Enter word2"). /** * A program that asks three words from the user using the JOptionPane * and then displays these three words as a phrase on the screen */ public class LastThreeWords { public static void main(String[] args){ //gets the first word from the user String firstWord = JoptionPane.2 Last 3 words (JOptionPane version) import javax. } } Introduction to Programming I 262 .J.E. //gets the third word from the user String thirdWord = JoptionPane.showInputDialog ("Enter word3").
/** * Gets three number inputs from the user * then displays the average on the screen */ public class Grades { public static void main(String[] args){ //declares the variable reader as the BufferedReader reader = new BufferedReader ( new InputStreamReader( System.J.out.out.print("Third grade: ").readLine()). int thirdGrade = 0. //prints the average of the three exams System. int secondGrade = 0. System.in)).out.parseInt (reader.readLine()).print(" .print(" . try{ System.-("). } } Introduction to Programming I 263 .1 Grades Using BufferedReader: import java. secondGrade = Integer. double average = 0.out.E. } //solves for the average average = (firstGrade+secondGrade+thirdGrade)/3.I Chapter 6 Exercises 6.io.print("Average: "+average). firstGrade = Integer. System.D.parseInt (reader. else System.exit(0).println("Input is invalid").-)"). System.readLine()).print("First grade: "). }catch( Exception e){ System. if(average>=60) System. thirdGrade = Integer.*.out. int firstGrade = 0.out.print("Second grade: ").parseInt (reader.out.
J.I Using JOptionPane: import javax. } else{ JoptionPane."Average : "+average+" .showInputDialog ("First grade")). if(average>=60){ JoptionPane.showMessageDialog(null. average = 0.parseDouble (JoptionPane.showMessageDialog (null. "Input is invalid").E.showMessageDialog (null.-("). System. /** * Gets three number inputs from the user * then displays the average on the screen */ public class Grades { public static void main(String[] args){ double double double double try{ firstGrade = 0. secondGrade = 0.JOptionPane. } //solves for the average average = (firstGrade+secondGrade+thirdGrade)/3."Average : "+average+" . } } } Introduction to Programming I 264 .showInputDialog ("Third grade")).swing.exit(0).showInputDialog ("Second grade")).parseDouble (JoptionPane. firstGrade = Double.D. thirdGrade = Double.-)"). }catch( Exception e){ JoptionPane. secondGrade = Double.parseDouble (JOptionPane. thirdGrade = 0.
else if(input == 5) msg = "five".showInputDialog ("Enter number")).2 Number in words Using if-else statement: import javax.JOptionPane. else if(input == 6) msg = "six". //gets the input string input = Integer. else if(input == 2) msg = "two". //sets msg to the string equivalent of input if(input == 1) msg = "one". else if(input == 9) msg = "nine".parseInt(JOptionPane. else if(input == 10) msg = "ten".msg).swing.J. else if(input == 3) msg = "three". } } Introduction to Programming I 265 . else if(input == 8) msg = "eight". //displays the number in words if with in range JOptionPane. /** * Transforms a number input from 1-10 to words * using if-else */ public class NumWords { public static void main(String[] args){ String msg = "".I 6. else if(input == 7) msg = "seven".E.showMessageDialog(null.D. else if(input == 4) msg = "four". else msg = "Invalid number". int input = 0.
case 7: msg = "seven". break.I Using switch statement: import javax. break. case 9: msg = "nine". //sets msg to the string equivalent of input switch(input){ case 1: msg = "one".JOptionPane. case 3: msg = "three".D. case 2: msg = "two".J. case 4: msg = "four".showMessageDialog(null. break. */ public class NumWords { public static void main(String[] args){ String msg = "". break.showInputDialog ("Enter number")).msg). //gets the input string input = Integer. case 5: msg = "five". case 6: msg = "six". break. int input = 0.E. } //displays the number in words if with in range JOptionPane. break.parseInt (JOptionPane. break. break. break. default: msg = "Invalid number". break. break. /** * Transforms a number input from 1-10 to words * using switch.swing. case 8: msg = "eight". } } Introduction to Programming I 266 . case 10: msg = "ten".
out.println("Invalid input").io. int counter = 0.I 6.E.exit(0). } //while loop that prints the name one hundred times while(counter < 100){ System. //gets the users' name try{ System.print("Enter name: ").in)). } } } Introduction to Programming I 267 .D.3 Hundred Times Using while-loop: import java.out.J.out.*. /** * A program that prints a given name one hundred times * using while loop */ public class HundredNames{ public static void main(String[] args){ BufferedReader reader = new BufferedReader (new InputStreamReader ( System. }catch(Exception e){ System. name = reader. System. String name = "".println(name). counter++.readLine().
println("Invalid input").print("Enter name: "). counter++.out.out. }while(counter < 100).println(name).out. } } Introduction to Programming I 268 . }catch(Exception e){ System.exit(0). /** * A program that prints a given name one hundred times * using do-while loop */ public class HundredNames { public static void main(String[] args){ BufferedReader reader = new BufferedReader (new InputStreamReader ( System. name = reader.*.D.I Using do-while loop: import java. int counter = 0.readLine(). } times //do-while loop that prints the name one hundred do{ System. //gets the users' name try{ System.E.io.in)).J. System. String name = "".
counter < 100. //gets the users' name try{ System.exit(0). name = reader.io.out.D.out.I Using for loop: import java.E. counter++){ System.in)).out.println(name).println("Invalid input"). /** * A program that prints a given name one hundred times * using do-while loop */ public class HundredNames { public static void main(String[] args){ BufferedReader reader = new BufferedReader (new InputStreamReader ( System. } //for loop that prints the name one hundred times for(int counter = 0. }catch(Exception e){ System. String name = "".print("Enter name: "). } } } Introduction to Programming I 269 . System.*.readLine().J.
*/ public class Powers { public static void main(String[] args){ int int int int base = 0. exp = Integer.showInputDialog("Exponent")). } //while loop that solves for the power while(counter < exp){ power = power*base. } } Introduction to Programming I 270 . power = 1.parseInt (JOptionPane. System.showMessageDialog (null.4 Powers Using while-loop: import javax.I 6.base+" to the "+exp+ " is "+power).E.D. The exponent is limited to positive numbers only.showInputDialog("Base")).exit(0). counter++.J."Positive numbers only please"). } //displays the result JoptionPane. //limits the exp to positive numbers only if(exp < 0 ){ JoptionPane.parseInt (JOptionPane.showMessageDialog (null. /** * Computes the power of a number given the base and the * exponent. //gets the user input for base and power using // JOptionPane base = Integer.swing. counter = 0. exp = 0.JOptionPane.
E.parseInt(JOptionPane. The exponent is limited to positive numbers only."Positive numbers only please"). //displays the result JoptionPane. exp = 0.I Using do-while loop: import javax. power = 1.showMessageDialog (null.showMessageDialog(null.exit(0). } } Introduction to Programming I 271 .J. System. */ public class Powers { public static void main(String[] args){ int int int int base = 0.swing. counter = 0.D. //limits the exp to positive numbers only if(exp < 0 ){ JoptionPane. } //do-while loop that solves the power given the base // and exponent do{ if(exp != 0) power = power*base.JOptionPane. exp = Integer.parseInt(JOptionPane. }while(counter < exp).showInputDialog ("Exponent")). //gets the user input for base and power //using JOptionPane base = Integer.base + " to the "+exp + " is "+power).showInputDialog ("Base")). /** * Computes the power of a number given the base and the * exponent. counter++.
JOptionPane."Positive numbers only please").parseInt(JOptionPane. System.J. } } Introduction to Programming I 272 . } //for loop for computing the power for(counter = 0.E.I Using for loop: import javax.base + " to the "+exp + " is "+power).D. power = 1. counter++){ power = power*base.swing. The exponent is limited to positive numbers only.exit(0).showInputDialog ("Exponent")). counter < exp. counter = 0.showInputDialog ("Base")). exp = Integer.parseInt(JOptionPane. exp = 0. //gets the user input for base and power using // JOptionPane base = Integer. */ public class Powers { public static void main(String[] args){ int int int int base = 0. //limits the exp to positive numbers only if(exp < 0 ){ JoptionPane.showMessageDialog(null. } //displays the result JoptionPane. /** * Computes the power of a number given the base and the * exponent.showMessageDialog(null.
int counter = 0."Friday". */ public class DaysOfTheWeek { public static void main(String[] args){ //declares the String array of the days of // the week String[] days ={"Sunday".length). "Saturday"}. int counter = 0.out."Thursday".J.D."Monday".1 Days of the Week Using while loop: /** * Uses an array string to save the days of the wee * then prints it on the screen. //while loop that prints the days of the week while(counter < days."Friday".length){ System."Tuesday". "Wednesday". "Saturday"}."Tuesday"."Monday".E. counter++. } } Introduction to Programming I 273 . } } } Using do-while loop: /** * Uses an array string to save the days of the wee * then prints it on the screen with a do-while loop.out.I Chapter 7 Exercises 7. //do-while loop that prints the days of the // week do{ System."Thursday".println(days[counter]). "Wednesday". counter++. }while(counter < days.println(days[counter]). */ public class DaysOfTheWeek { public static void main(String[] args){ //declares the String array of the days of the week String[] days = {"Sunday".
//gets the maximum number if((counter == 0)||(num[counter] > max)) max = num[counter]. Introduction to Programming I 274 . counter < 10. "Wednesday".showMessageDialog(null.length. */ public class DaysOfTheWeek { public static void main(String[] args){ //declares the String array of the days of // the week String[] days ={"Sunday". "Saturday"}.J.JOptionPane. int max = 0.println(days[counter]). int counter."Thursday".E. //for loop that gets the 10 numbers from the user for(counter = 0.showInputDialog( "Enter number "+(counter+1))). //for loop that prints the days of the week for(int counter = 0. counter < days."Monday".parseInt (JoptionPane.out.2 Greatest number import javax. counter++) } } 7. */ public class GreatestNumber { public static void main(String[] args){ int[] num = new int[10]."Friday". /** * A program that uses JOptionPane to get ten numbers * from the user then outputs the largest number. } } } //displays the number with the greatest number JoptionPane.swing. System. "The number with the greatest value is "+max).D.I Using for loop: /** * Uses an array string to save the days of the wee * then prints it on the screen with a for loop. counter++){ num[counter] = Integer."Tuesday".
D. } } } Introduction to Programming I 275 .println(args[counter]). */ public class CommandLineSample { public static void main(String[] args){ //checks if a command line argument exists if(args.I Chapter 8 Exercises 8. //for loop that prints the arguments from the //command line for(int counter=0.length == 0) System.1 Print Arguments /** * A program that prints the string from the command line if any. counter++){ System.length.J.out.E.counter<args.exit(0).
//4. } } Class and Method declaration: 1. System. Class: System Method: public static void exit( int status ) 4. //5.isDigit('0')).exit(1). Class: Character Method: public static boolean isDigit( char ch ) Introduction to Programming I 276 . endsWith String str = "Hello". Class: String Method: public boolean endsWith( String suffix ) 2. Class: Math Method: public static double floor( double a ) 5.endsWith( "slo" ) ).out. 16) ).println( Math.1 Defining terms See definitions in book. forDIgit System.E. System. int radix ) 3. exit was not called").out.14)). //2.I Chapter 9 Exercises 9. Check the Java API for more answers. Class: Character Method: public static char forDigit( int digit.out. System.println( str.J. floor System. System.out.println("if this is executed.isDigit('A')). //3.println( "0=" + Character.out.floor(3.2 Java Scavenger Hunt To the teacher: These are just some sample methods in the Java API that you can use.forDigit(13.println( Character.println( "A=" +Character. 9.out. isDigit System. Sample Usage: public class Homework1 { public static void main(String []args){ //1.D.
add = add. int tel.I Chapter 10 Exercises 10. } /** * changes the variable name */ public void changeName(String name){ this. this. telephone number and email adress */ public AddressBookEntry(String name. address. String add. telephone number.tel = tel. } /** * Creates an AddressBookEntry object with the given * name. tel = 0.E.1 Address Book Entry /** * An address book class that record a persons * name. String email){ this. /** * default constructor */ public AddressBookEntry(){ name = "". email = "". add = "". and email address */ public class AddressBookEntry { private private private private String name. String email.name = name. this.D. address. int tel. this. String add.email = email. } /** * returns the variable add */ public String getAddress(){ return add. } Introduction to Programming I 277 .J. } /** * returns the variable name */ public String getName(){ return name.name = name.
D.J. } } Introduction to Programming I 278 . } /** * changes the variable tel */ public void changeTelNumber(int tel){ this. } /** * returns the variable tel */ public int getTelNumber(){ return tel. } /** * changes the variable email */ public void changeEmailAdd(String email){ this.tel = tel.E. } /** * returns the variable email */ public String getEmailAdd(){ return email.email = email.add = add.I /** * changes the variable add */ public void changeAddress(String add){ this.
/** * Creates an addresbook that contains 100 AddressBookEntries */ public class AddressBook { //index of the last entry private int top = 0. } Introduction to Programming I 279 .io. }catch(Exception e){ System. System. //array of Address Book Entries private AddressBookEntry[] list.*.out. System.readLine(). AddressBook addBook = new AddressBook(). System.J. /** * The main method */ public static void main(String[] args){ BufferedReader keyIn = new BufferedReader (new InputStreamReader (System.E.println("[Q] Quit"). try{ //gets the choice act = keyIn.println("Error").D.println("\n[A] Add entry"). //constant number that indicates the maximum //number of entries in the address book private static final int MAXENTRIES = 100.in)).out.out.println("[D] Delete entry").out.print("Enter desired action: ").out.println("[U] Update entry"). System. String act = "".println("[V] View all entries").out.I 10.out. while(true){ //displays the optons System.2 AddressBook import java. System.
out. Introduction to Programming I 280 .equals("U")||act.E.equals("A")||act.equals("d")) addBook.I } } //checks for the appropriate action for // his choice if(act.viewEntries().println ("Unknown command").addEntry().equals("D")||act.equals("V")||act. else if(act. else if(act.equals("Q")||act.equals("v")) addBook.D.J.delEntry().exit(0).equals("a")) addBook. else if(act.equals("q")) System.equals("u")) addBook.updateEntry(). else if(act. else System.
} AddressBookEntry entry = new AddressBookEntry (name. return. email).D.out.readLine(). }catch(Exception e){ System. } Introduction to Programming I 281 .J.print("Email Adress: ").readLine()).parseInt(keyIn. int tel = 0. add = keyIn.readLine(). } //asks the user for the data of the address book try{ System.println(e). tel.E.I /** * creates the AddressBook */ public AddressBook(){ list = new AddressBookEntry[MAXENTRIES]. top++. if(top == MAXENTRIES){ System. add.print("Address: "). System.out.print("Telephone number: ").print("Name: "). email = keyIn.exit(0). String add = "". list[top] = entry.out. tel = Integer. } /** * method for adding an AddressBookEntry to the Adressbook */ public void addEntry(){ BufferedReader keyIn = new BufferedReader (new InputStreamReader (System.readLine().out. System.out.println("Address Book is full"). String name = "". System. String email = "". System.out. name = keyIn.in)).
J. i++ ){ list[i] = list[i+1].println("Address:"+ list[index]. }else{ for( int i=index.out. System. int index = 0.println("Index Out Of Bounds").out.out.parseInt(keyIn.D.out. }catch(Exception e){} //checks if the index is with in bounds if(index < 0 || index >= top){ System. } } /** * method that prints all the entries in the AddressBook */ public void viewEntries(){ for(int index = 0. } } Introduction to Programming I 282 . } //asks for the entry which is to be deleted try{ //shows the current entries on the record book viewEntries(). //checks if the address book is empty if(top == 0){ System.out.E. i<top. index = Integer. index++){ System.in)).getTelNumber()).I /** * method that deletes an AddressBookEntry from the * Adressbook with the index */ public void delEntry(){ BufferedReader keyIn = new BufferedReader (new InputStreamReader(System. return.println((index+1)+" Name:"+ list[index]. System. } list[top] = null. System.getAddress()). return.getEmailAdd()). index < top.getName()). System.println("Address Book is empty").print("\nEnter entry number: ").println("Email Address:"+ list[index].out.println("Telephone Number:"+ list[index]. top--.readLine())-1.out.
int index = 0.in)). String add = "".print("Name: "). } //updates the entry AddressBookEntry entry = new AddressBookEntry (name. int tel = 0.out. list[index] = entry.print("Email Adress: ").readLine().readLine(). }catch(Exception e){ System. tel. email = keyIn. System.print("Telephone number: "). String name = "".I /** * method that updates an entry */ public void updateEntry(){ BufferedReader keyIn = new BufferedReader(new InputStreamReader (System. //asks for the entries data try{ System. System.readLine(). System.out. index =Integer.print("Entry number: ").parseInt(keyIn.J.E.exit(0). add = keyIn.readLine())-1.D.out. System. } } Introduction to Programming I 283 .out.out. name = keyIn. System. email). tel = Integer.println(e). add. String email = "".readLine()).parseInt(keyIn.out.print("Address: ").
D. protected double mathGrade. } /** * Returns the age of the student */ public int getAge(){ return age. } /** * Changes the address of the student */ public void setAddress(String temp){ address = temp. protected double englishGrade. protected static int studentCount. } /** * Changes the name of the student */ public void setName(String temp){ name = temp.E. } /** * Returns the address of the student */ public String getAddress(){ return address. } /** * Changes the age of the student */ public void setAge(int temp){ age = temp. protected String address.I Chapter 11 Exercises 11. /** * Returns the name of the student */ public String getName(){ return name. protected double scienceGrade. } Introduction to Programming I 284 . protected int age.J.1 Extending StudentRecord /** * An object that holds the data for a student */ public class StudentRecord { protected String name. protected double average.
} /** * Changes the englishGrade of the student */ public void setEnglishGrade(double temp){ englishGrade = temp. } /** * Returns the mathGrade of the student */ public double getMathGrade(){ return mathGrade.J. } /** * Returns the scienceGrade of the student */ public double getScienceGrade(){ return scienceGrade.I /** * Returns the englishGrade of the student */ public double getEnglishGrade(){ return englishGrade. math and * science grades */ public double getAverage(){ return (mathGrade+englishGrade+scienceGrade)/3.E. } /** * Returns the number of instances of the * StudentRecords */ public static int getStudentCount(){ return studentCount. } /** * Computes the average of the english.D. } /** * Changes the scienceGrade of the student */ public void setScienceGrade(double temp){ scienceGrade = temp. } /** * Changes the mathGrade of the student */ public void setMathGrade(double temp){ mathGrade = temp. } } Introduction to Programming I 285 .
} /** * Changes the studentNumber of the student */ public void setStudentNumber(String temp){ studentNumber = temp. } } Introduction to Programming I 286 .D. } /** * Changes the comSciGrade of the student */ public void setComSciGrade(double temp){ comSciGrade = temp. } /** * Returns the comSciGrade of the student */ public double getComSciGrade(){ return comSciGrade.I /** * A student record for a Computer Science student */ public class ComputerScienceStudentRecord extends StudentRecord { private String private double studentNumber.E.J. comSciGrade. /** * Returns the studentNumber of the student */ public String getStudentNumber(){ return studentNumber.
} /** * returns shape name */ public String getName(){ return "circle". } /** * Class definition for object circle */ public class Circle extends Shape { private static final double pi = 3.E. } } Introduction to Programming I 287 . } /** * returns area */ public double getArea(){ return pi*radius*radius. /** * returns the name of the shape */ public abstract String getName(). private double radius = 0.D.2 Abstract Classes /** * Definition of shape abstract class */ public abstract class Shape { /** * returns the area of a certain shape */ public abstract double getArea().J. } /** * set radius */ public void setRadius(double r){ radius = r. } /** * returns radius */ public double getRadius(){ return radius. /** * Constructor */ public Circle(double r){ setRadius( r ).I 11.1416.
I /** * Class definition for object square */ public class Square extends Shape { private double side = 0. } } Introduction to Programming I 288 . } /** * returns area */ public double getArea(){ return side*side.J. } /** * returns shape name */ public String getName(){ return "square". /** * Constructor */ public Square(double s){ setSide( s ).D.E. } /** * returns length of one side */ public double getSide(){ return side. } /** * set length of side */ public void setSide(double s){ side = s.
} } } //displays the number with the greatest number JoptionPane. wherein we included some exception handling. } } } 12. } }catch( ArrayIndexOutOfBoundsException e ){ System. int counter. System.I Chapter 12 Exercises 12.showInputDialog ("Enter number "+(counter+1))).E.D. int max = 0."). /** * A program that uses JOptionPane to get ten numbers * from the user then outputs the largest number.JOptionPane.parseInt (JoptionPane.showMessageDialog (null.showMessageDialog (null. import javax."The number with the greatest value is "+max).J. } //gets the maximum number if((counter == 0)||(num[counter] > max)) max = num[counter]. //for loop that gets the 10 numbers from the user for(counter = 0.swing. true.out. }catch(NumberFormatException e){ JoptionPane.println("Exception caught:"). System.println(" "+e).2 Catching Exceptions 2 Here are three sample programs that we did before. counter++){ try{ num[counter] = Integer.out..out. counter < 10. */ public class GreatestNumber { public static void main(String[] args){ int[] num = new int[10].println("args["+i+"]="+args[i]).println("Quiting.1 Catching Exceptions 1 public class TestExceptions{ public static void main( String[] args ){ try{ for( int i=0..out."Error "+e). i++ ){ System. Introduction to Programming I 289 .
case 6: msg = "six". Introduction to Programming I 290 try{ . */ public class NumWords { public static void main(String[] args){ String msg = "".I import javax. break. break. case 5: msg = "five". break.J.showMessageDialog(null. } //sets msg to the string equivalent of input switch(input){ case 1: msg = "one". break. break. } //displays the number in words if with in range JOptionPane. }catch(Exception e){ JOptionPane. case 4: msg = "four".swing.showMessageDialog(null. case 10: msg = "ten". case 2: msg = "two". case 9: msg = "nine". break. /** * Transforms a number input from 1-10 to words using switch.D. int input = 0. case 7: msg = "seven". break. case 8: msg = "eight". break.showInputDialog ("Enter number")). break.parseInt (JoptionPane. case 3: msg = "three"."Invalid input"). //gets the input string input = Integer. break.E.exit(0).msg). System. default: msg = "Invalid number". break.JOptionPane.
J.E.D.I
} } import javax.swing.JOptionPane; /** * Computes the power of a number given the base and the exponent. * The exponent is limited to positive numbers only. */ public class Powers { public static void main(String[] args){ int int int int base = 0; exp = 0; power = 1; counter = 0;
//gets the user input for base and power using JOptionPane try{ base = Integer.parseInt (JoptionPane.showInputDialog ("Base")); exp = Integer.parseInt (JoptionPane.showInputDialog ("Exponent")); }catch(NumberFormatException e){ JoptionPane.showMessageDialog (null,"Input Error"); System.exit(0); } //limits the exp to positive numbers only if(exp < 0 ){ JoptionPane.showMessageDialog (null,"Positive numbers only please"); System.exit(0); } //for loop for computing the power for(;counter < exp;counter++){ power = power*base; } //displays the result JoptionPane.showMessageDialog (null,base+" to the "+exp +" is "+power);
}
}
Introduction to Programming I
291
J.E.D.I
Appendix D : Machine Problems Machine Problem 1: Phone Book
Write a program that will create an phonebook, wherein you can add entries in the phonebook, delete entries, view all entries and search for entries. In viewing all entries, the user should have a choice, whether to view the entries in alphabetical order or in increasing order of telephone numbers. In searching for entries, the user should also have an option to search entries by name or by telephone numbers. In searching by name, the user should also have an option if he/she wants to search by first name or last name. MAIN MENU 1 - Add phonebook entry 2 - Delete phonebook entry 3 - View all entries a - alphabetical order b - increasing order of telephone numbers 4 - Search entries a - by name b - by telephone number 5 – Quit The following will appear when one of the choices in the main menu is chosen. Add phonebook entry Enter Name: Enter Telephone number: (* if entry already exists, warn user about this) View all entries Displays all entries in alphabetical order Displays all entries in increasing order of telephone #s Search entries Search phonebook entry by name Search phonebook entry by telephone number Quit close phonebook
Introduction to Programming I
292
J.E.D.I
Machine Problem 2: Minesweeper
This is a one player game of a simplified version of the popular computer game minesweeper. First, the user is asked if he or she wants to play on a 5x5 grid or 10x10 grid. You have two 2-dimensional arrays that contains information about your grid. An entry in the array should either contain a 0 or 1. A 1 signifies that there is a bomb in that location, and a 0 if none. For example, given the array: int bombList5by5[][]={{0, 0, 1, 0, 0}, {0, 0, 0, 0, 0}, {0, 1, 0, 0, 0}, {0, 0, 0, 1, 1}, {0, 1, 1, 0, 0}}; Given the bomb list, we have 6 bombs on our list. The bombs are located in (row,col) cells, (0,2), (2,1), (3,3), (3,4), (4,1) and (4,2). If the user chooses a cell that contains a bomb, the game ends and all the bombs are displayed. If the user chooses a cell that does not contain a bomb, a number appears at that location indicating the number of neighbors that contain bombs. The game should end when all the cells that do not contain bombs have been marked (player wins) or when the user steps on a bomb(player loses). Here's a sample output of the game, given the bombList5by5. Welcome to Minesweeper! Choose size of grid (Press 1 for 5x5, Press 2 for 10x10): 1 [][][][][] [][][][][] [][][][][] [][][][][] [][][][][] Enter row and column of the cell you want to open[row col]: 1 1 [][][][][] [ ] [2] [ ] [ ] [ ] [ ] [ ] [] [ ] [ ] [][][][][] [][][][][] Enter row and column of the cell you want to open[row col]: 3 2 [][][][][] [ ] [2 ] [ ] [] [ ] [][][][][] [ ] [ ] [4 ] [ ] [ ] [][][][][] Enter row and column of the cell you want to open[row col]: 0 2 [] [ ] [ ] [ ] [ ] [ ] [2] [ ] [] [ ] [ ] [X ] [ ] [ ] [ ] [ ] [ ] [4] [ ] [ ] [][][][][] Ooppps! You stepped on a bomb. Sorry, game over!
Introduction to Programming I
293
J.E.D.I
Machine Problem 3: Number Conversion
Create your own scientific calculator that will convert the inputted numbers to the four number representations ( Decimal, Binary, Octal, Hexadecimal ). Your program should output the following menu on screen. MAIN MENU: Please type the number of your choice: 1 – Binary to Decimal 2 – Decimal to Octal 3 – Octal to Hexadecimal 4 – Hexadecimal to Binary 5 – Quit The following will appear when one of the choices in the main menu is chosen. Choice 1: Enter a binary number: 11000 11000 base 2 = 24 base 10 (goes back to main menu) Choice 2: Enter a Decimal number: 24 24 base 10 = 30 base 8 (goes back to main menu) Choice 3: Enter an Octal number: 30 30 base 8 = 18 base 16 (goes back to main menu) Choice 4: Enter a Hexadecimal number: 18 18 base 16 = 11000 base 2 Choice 1: Enter a binary number: 110A Invalid binary number! Enter a binary number: 1 1 base 2 = 1 base 10 (goes back to main menu) (user chooses 5) Goodbye! You can be more creative with your user interface if you want to, as long as the program outputs the correct conversion of numbers.
Introduction to Programming I
294
J.E.D.I
Appendix E : Hands-on Laboratory Note to the Teacher
This part of the manual is not included in the student's manual. You can give a copy of this to your students if you wish for them to do the exercises on their own. Some of the answers for "Creating your own" exercises are found in the last part of this section.
Chapter 1 Hands-on
None
Chapter 2 Hands-on
None
Introduction to Programming I
295
J.E.D.I
Chapter 3 Hands-on
3.1 Things to check before you start the lab
Once you installed J2SE SDK, please make sure you do the following: 1. Make sure the installation has set %JAVA_HOME% (Windows) or $JAVA_HOME (Solaris/Linux) environment variable to the installation directory of J2SE 1.4.2_06 (or later version) 2. Type "echo %JAVA_HOME%" (Windows) or "echo $JAVA_HOME" (Solaris/Linux) in a terminal window. You should see the following: c:\j2sdk1.4.2_06 (Windows) /usr/jdk/jdk1.4.2_06 (Solaris/Linux) 3. Make sure the installation has placed %JAVA_HOME%\bin (Windows) or $JAVA_HOME/bin (Solaris/Linux) in the "path" environment variable. Type "java -version" in a terminal window. You should see something like following: java version "1.4.2_06" Java(TM) 2 Runtime Environment, Standard Edition (build 1.4.2_06-b03) Java HotSpot(TM) Client VM (build 1.4.2_06-b03, mixed mode)
Introduction to Programming I
296
J.E.D.I
3.2 Write, Compile, and Run Hello Java Program
1. mkdir c:\lab 2. cd \lab 3. Create Hello.java using your editor of choice public class Hello { /** * My first Java program */ public static void main( String[] args ){ //prints the string "Hello world" on screen System.out.println("Hello world"); } }
4. Compile Hello.java javac Hello.java 5. Make sure Hello.class file has been created dir 6. Run the Hello program java Hello 7. Verify that the result is as following C:\lab>java Hello Hello world 8. Modify, compile, and run the Hello.java so that it prints the following "This is my first Java program" (instead of "Hello world")
Introduction to Programming I
297
I 3.java code in the source editor with the one in Chapter 2 while leaving the package statement on the top. Compile. Run Hello class • • Right click Hello. Modify the Hello class • Replace the code of Hello class of IDE generated Hello. and Run Hello Java Program using NetBeans 1.1 • • Windows: Start > All Programs > NetBeans 4.java code gets displayed in the source editor.Main) • Click Finish (from Figure 12. fill it with Hello • For Create Main Class field.D.java node under Hello->Source Packages->hello and select Run File (Shift+F6) Note that the Output window displays the result Introduction to Programming I 298 . Create a new NetBeans project and Hello main class • • • • Select File from the menu bar and select New Project. select General and Java Application Click Next. Start the NetBeans IDE 4. Under Choose Project. Under Name and Location pane. 4. 3.3 Write.E.1 > NetBeans IDE or click NetBeans IDE 4.Hello hello.1 desktop icon Solaris/Linux: <NETBEANS41_HOME>/bin/netbeans 2. change it to hello.J.60 :Create new Java application • Note that the IDE generated Hello. (Figure-10 below) • For Project Name field.
Initializing.java java OutputVariable 3. } } 2. Print out the value of grade variable as following System.java using your editor of choice public class OutputVariable { public static void main( String[] args ){ int value = 10.I Chapter 4 Hands-on 4. x = 'A'. Verify that the result is as following C:\lab>java OutputVariable 10 The value of x=A 4. Printing Variables 1. Create OutputVariable. Introduction to Programming I 299 .out. char x. System.E.out.D.println( "The value of x=" + x ).1 Declaring.java as following and compile and run the code • • Define another primitive type as following double grade = 11.println( value ).J. Modify OutputVariable. Compile and run the code javac OutputVariable.println( "The value of grade =" + grade ).out. System.
E. Verify that the result is as following C:\lab>java ConditionalOperator Passed 4.I 4. compile and run the code int salary = 100000. } } 2.out. Compile and run the code javac ConditionalOperator.java using your editor of choice public class ConditionalOperator { public static void main( String[] args ){ String status = "". Modify ConditionalOperator.D.J. Print "poor" otherwise. Introduction to Programming I 300 . Print "rich" if the salary is over 50000. //get status of the student status = (grade >= 60)?"Passed":"Fail". //print status System.java java ConditionalOperator 3.println( status ). Create ConditionalOperator.2 Conditional Operator 1.java as following. int grade = 80.
in) ).D.java java GetInputFromKeyboard 3.out.J. } System.out.out.I Chapter 5 Hands-on 5.readLine(). }catch( IOException e ){ System.1 Getting Input From Keyboard via BufferedReader 1. compile and run the code • • Make the program to ask the following question Please enter your age Display the entered age as following • If the age is over 100.println("Hello " + name +"!").BufferedReader. Compile and run the code javac GetInputFromKeyboard. Modify GetInputFromKeyboard.InputStreamReader. display Hello <name> You are old! • Otherwise Hello <name> You are young! Introduction to Programming I 301 .java as following.java using your editor of choice import java. Create GetInputFromKeyboard. public class GetInputFromKeyboard { public static void main( String[] args ){ BufferedReader dataIn = new BufferedReader(new InputStreamReader( System. import java.IOException.io. try{ name = dataIn. } } 2. import java. String name = "".E.io.io. System.print("Please Enter Your Name:").println("Error!").
JOptionPane. } } 2. Create GetInputFromKeyboardJOptionPane.2 Getting Input From Keyboard via JOptionPane 1. Modify GetInputFromKeyboardJOptionPane.java java GetInputFromKeyboardJOptionPane Enter your name CTRL/C to close the application 3.showMessageDialog(null. msg).D. compile and run the code • • Make the program to ask the following question Please enter your age Display the entered age as following • If the age is over 100. Compile and run the code javac GetInputFromKeyboardJOptionPane.J. display Hello <name> You are old! • Otherwise Hello <name> You are young! Introduction to Programming I 302 .java as following. name=JOptionPane. public class GetInputFromKeyboardJOptionPane { public static void main( String[] args ){ String name = "". String msg = "Hello " + name + "!".E.JOptionPane.I 5.swing.showInputDialog("Please enter your name").java using your editor of choice import javax.
length."Bianca".i<names. } } if (foundName ) System.java using your editor of choice public class ForLoop { public static void main( String[] args ){ String names []= {"Beah".out."Lance".i++){ if (names [i ]. Compile and run the code javac ForLoop."Belle"."Ethan"}. Create ForLoop. break. boolean foundName =false.out."Yza". Modify ForLoop."Gem". } } 2.java as following.equals(searchName )){ foundName =true. compile and run the code • Change the code to use while loop Introduction to Programming I 303 .I Chapter 6 Hands-on 6. String searchName ="Yza".E.").D.J. else System."Nico".1 For Loop 1. Verify that the result is as following C:\lab>java ForLoop Yza is found! 4.println(searchName +" is not found.java java ForLoop 3. for (int i=0.println(searchName +" is found!").
Modify ArraySample. } } } 2.print( ages[i] ).out. Create ArraySample. i<ages.I Chapter 7 Hands-on 7. 101 to the next entry of the array.D. for( int i=0. ages[0].java java ArraySample 3. ages[1]. compile and run the code • Just before the for loop that prints out the value of each entry of the ages[] array.length.java as following. create another for loop in which a value of 100 is assigned to the first entry of the array.1 Arrays 1. and so on Introduction to Programming I 304 . Compile and run the code javac Arraysample.java using your editor of choice public class ArraySample { public static void main( String[] args ){ int[] ages = new int[100]. Verify the result is as following C:\lab>java ArraySample 000000000000000000000000000000000000000000000000000000000000000 00000000000000000 00000000000000000000 4.J. i++ ){ System.E.
out. //Call method test //and pass i to method test test( i ). Verify the result is as following C:\lab>java TestPassByValue 10 10 Introduction to Programming I 305 . } } 2. Create .E.J.out.I Chapter 8 Hands-on None Chapter 9 Hands-on 9.java using your editor of choice public class TestPassByValue { public static void main(String[] args){ int i = 10. //print the value of i System.println(i). i not changed System.D.1 Pass-by-Value 1.java java TestPassByValue 3. Compile and run the code javac TestPassByValue. } public static void test(int j){ // change value of parameter i j = 33.println(i). // print the value of i.
i++ ){ System. Verify the result is as following C:\lab>java TestPassByReference 10 11 12 50 51 52 Introduction to Programming I 306 .2 Pass-by-Reference 1. //print array values for (int i=0. //print array values again for (int i=0.java java TestPassByReference 3.java using your editor of choice public class TestPassByReference { public static void main(String[] args){ //create an array of integers int [] ages = {10. i<ages. } } public static void test(int[] arr){ // change values of array for (int i=0. 11. Create .out. } //call test and pass references to array test(ages). i<arr.println(ages[i]). i<ages.J. Compile and run the code javac TestPassByReference.length.I 9. i++ ){ arr[i] = i + 50.out.println(ages[i]).length. i++ ){ System.D.length. 12}.E. } } } 2.
integer1 = new Integer(5).D.J.java class EqualsTestInteger { public static void main(String[] arguments) { Integer integer1. .println("String2: " + str2).out. System.println("Same object? " + (str1 == str2)).println("Same value? " + str1. Compile and run the code javac EqualsTest.out. str2 = new String(str1).println("Integer2: " + integer2). Create EqualsTest.out.println("Same object? " + (str1 == str2)).I 9.E.println("Integer1: " + integer1). integer2. Create EqualsTestInteger. System.java java EqualsTestInteger Introduction to Programming I 307 periodicals. integer2 = new Integer(5). System.equals (integer2)).println("Integer1: " + integer1).3 Comparing Objects 1. integer1 = integer2.". str2 = str1. System.out.println("String1: " + str1).out. System.out. periodicals. System. System.out. str2.out. System. System.java using your editor of choice class EqualsTest { public static void main(String[] arguments) { String str1. str1 = "Free the bound periodicals.out. C:\lab>java EqualsTest String1: Free the bound String2: Free the bound Same object? true String1: Free the bound String2: Free the bound Same object? false Same value? true 4.out.out.out. } } 2.out.println("Same object? " + (integer1 == integer2)).java java EqualsTest 3. Verify the result is as following.println("Same object? " + (integer1 == integer2)).println("Same value? " + integer1.println("String1: " + str1).equals(str2)). System.out. System. System. periodicals.println("String2: " + str2). System. Compile and run the code javac EqualsTestInteger. periodicals. System. } } 5.println("Integer2: " + integer2).
return result. Create StudentRecordExample. result =(mathGrade+englishGrade+scienceGrade )/3.J.E. Create StudentRecord. } /** *returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount.D. Introduction to Programming I 308 . } } 2.java using your editor of choice public class StudentRecord { // instance variables private String name.I Chapter 10 Hands-on 10. private double average. } /** *Computes the average of the english. private double mathGrade. /** *Returns the name of the student */ public String getName(){ return name. private double englishGrade.1 Create your own class Using Text Editor: 1. } /** *Changes the name of the student */ public void setName(String temp ){ name =temp. private double scienceGrade.math and science *grades */ public double getAverage(){ double result =0. // static variables private static int studentCount = 0.java using your editor of choice public class StudentRecordExample{ public static void main(String [] args ){ //create three objects for Student record StudentRecord annaRecord =new StudentRecord().
java StudentRecordExample.println(annaRecord. //set the name of the students annaRecord.setName("Cris").println ("Count="+StudentRecord. } } 3. Verify the result C:\lab1>java StudentRecordExample Anna Count=0 Introduction to Programming I 309 . StudentRecord crisRecord =new StudentRecord(). //print anna's name System. crisRecord. //print number of students System.getName()).I StudentRecord beahRecord =new StudentRecord().java) java StudentRecordExample 4.setName("Anna").out.java (or javac StudentRecord.E.D.out. beahRecord.J.setName("Beah"). Compile and run the code javac *.getStudentCount()).
J.E. Start the NetBeans IDE 4. select General and Java Application Click Next. (Figure-10 below) For Project Name field. change it to studentrecordexample.java code in the source editor with the one you have written before. 4.1 > NetBeans IDE or click NetBeans IDE 4. Modify the NetBeans generated code • Replace the NetBeans generated StudentRecordExample. Create a new NetBeans project and StudentRecordExample main class • • • • • • • Select File from the menu bar and select New Project. Write StudentRecord.1 (if you have not done so yet) • • Windows: Start > All Programs > NetBeans 4.Main) Click Finish 3.I Using Netbeans: 1. fill it with StudentRecordExample For Create Main Class field.StudentRecordExample (from studentrecordexample.D.1 desktop icon Solaris/Linux: <NETBEANS41_HOME>/bin/netbeans 2. Under Choose Project.java Introduction to Programming I 310 . Under Name and Location pane.
6. Modify the NetBeans generated code • Replace the NetBeans generated StudentRecord.java code in the source editor with the one you have written before.java node under Hello->Source Packages>studentrecordexample and select Run File (Shift+F6) Note that the Output window displays the result Introduction to Programming I 311 . choose studentrecordexample from the drop-down menu (or you can type studentrecordexample) Click Finish 5. Run StudentRecordExample application • • Right click StudentRecordExample. The New Java Class window appears. for Class Name field.D.E. type StudentRecord for Package field.J. Under Name and Location pane.I • • • Right click StudentRecordExample project node and select New->Java Class.
call it myOwnRecord Call setName() method of the myOwnRecord object passing "myOwn" as the value to set Display the name of the myOwnRecord object Set Math grade of myOwnRecord object Set English grade of myOwnRecord object Set Science grade of myOwnRecord object Display the average grade of myOwnRecord 3.J. Modify StudentRecordExample. this method increase the static variable studentCount by 1 2. Run StudentRecordExample application Introduction to Programming I 312 .java as following • • • • • • • Create another StudentRecord object.. Modify StudentRecord.E.java as following • • • • Add setMathGrade(double grade) method Add setEnglishGrade(double grade) method Add setScienceGrade(double grade) method Add static method called increaseStudentCount().I Creating your own: 1.D.
If you experience compile errors. } } 3. Verify the result Name:Anna Name:Anna Average Grade:65..J. annaRecord.16666666666667 Introduction to Programming I 313 .setName("Anna").) methods. annaRecord. public void print(String name ){ System.5). Compile and run the code. annaRecord.println("Average Grade:"+averageGrade). annaRecord. Add two overloaded print(.out.java as follows public class StudentRecordExample2{ public static void main(String [] args) { StudentRecord annaRecord =new StudentRecord().Create StudentRecordExample2.setEnglishGrade(95. The code fragement that needs to be added is highlighted with bold. public class StudentRecord { . Modify StudentRecord.out. fix the compile errors.E.getName()).java as following.print(annaRecord.java StudentRecordExample2.. double averageGrade){ System. //overloaded methods annaRecord.setScienceGrade(100)..2 Overloading Using Text Editor: 1.out.getName().java) java StudentRecordExample2 4.getAverage()). System. annaRecord.print(annaRecord. javac *.I 10.print("Name:"+name+" "). } } 2.println("Name:"+name).D. } public void print(String name.java (or javac StudentRecord.
I Using Netbeans: It is assumed you are using the same NetBeans project you created in 10. Create StudentRecordExample2.E.java with the one of above while leaving the package statement at the top 4.java • • • • Right studentrecordexample package node (Not StudentRecordExample project node) and select New->Java Class Under Name and Location pane.D.1. Right click studentrecordexample package node (Not StudentRecordExample project node) and select Compile Package (F9) 5. type StudentRecordExamle2 Click Finish 3.J. 1.java • Replace the code of the NetBeans generated StudentRecordExample2. Modify the StudentRecord. for Class Name field. Right click StudentRecordExamle2 and select Run File Introduction to Programming I 314 .java 2. Modify the NetBeans generated StudentRecordExample2.
D.J.java as following • Add another print() method which takes the following three parameters • name • grade average • student count 2.I Creating your own: 1. Modify StudentRecord. Modify StudentRecordExmaple2.java as following • Invoke the newly added print() method Introduction to Programming I 315 .E.
E. return result.java and StudenRecordExample. please create StudentRecord. } } Introduction to Programming I 316 . /** *Returns the name of the student */ public String getName(){ return name. } /** *returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount.3 Packaging Please do this exercise at the command line instead of using NetBeans.J. private double scienceGrade. 0. If have used NetBeans to do the exercise 13 above.I 10. private double average. // static variables private static int studentCount = 0. private double englishGrade. result =(mathGrade+englishGrade+scienceGrade )/3. private double mathGrade.math and science *grades */ public double getAverage(){ double result =0. This is to learn the packaging structure without the help of NetBeans. } /** *Computes the average of the english. } /** *Changes the name of the student */ public void setName(String temp ){ name =temp.D.java as following public class StudentRecord { // instance variables private String name.
. Modify StudentRecord..java 4.getStudentCount()).getName()).. Modify StudentRecordExample. You will experience an NoClassDefFoundError exception. public class StudentRecord { .out. package studentpackage.println(annaRecord.out.ClassLoader.java as following to add a package statement. StudentRecord beahRecord =new StudentRecord(). Think about why you are getting this exception for a moment. //print number of students System. beahRecord.setName("Cris"). The code fragement that needs to be added is is in bold characters. public class StudentRecordExample{ . //print anna's name System.println ("Count="+StudentRecord.java as following to add a package statement. javac StudentRecord. crisRecord.lang.J. It is because the StudentRecordExample.java StudentRecordExample. package studentpackage.. //set the name of the students annaRecord. It is because the java runtime is trying to find StudentRecordExample. Run the code.NoClassDefFoundError: StudentRecordExample (wrong name: studentpackage/StudentRecordExample) at java. The code fragment that needs to be added is in bold characters.setName("Anna"). } } 1. Compile code.E. StudentRecord crisRecord =new StudentRecord(). • C:\lab>java StudentRecordExample Exception in thread "main" java.setName("Beah").D. } 2.lang. } 3.java now has a package statement which says the Java class file resides under studentpackage directory.class under studentpackage directory.I public class StudentRecordExample{ public static void main(String [] args ){ //create three objects for Student record StudentRecord annaRecord =new StudentRecord().defineClass0(Native 317 Introduction to Programming I .
URLClassLoader.lang.net.findClass (URLClassLoader.URLClassLoader.loadClass (ClassLoader.run (URLClassLoader.defineClass (SecureClassLoader.lang.java C:\lab>dir studentpackage Volume in drive C is S3A1256D004 Volume Serial Number is 447E-6EBC Directory of C:\lab\studentpackage 07/06/2005 07/06/2005 07/06/2005 07/06/2005 07/06/2005 Introduction to Programming I 12:39 12:39 12:40 12:16 12:40 PM PM PM PM PM <DIR> <DIR> .java:55) at java. Note that the class files are now created under studentpackage directory not in the current directory javac studentpackage\StudentRecord.security. 1.URLClassLoader$1. .defineClass (ClassLoader.access$100 (URLClassLoader.class 1.doPrivileged (Native Method) at java. Compile the code using a directory structure.ClassLoader.ClassLoader..loadClass (ClassLoader.java 6.java:187) at java.java:194) at java.net.I Method) at java.AccessController.java StudentRecordExample.lang.net.java \lab\studentpackage\StudentRecordExample.425 StudentRecord.java under it.499 StudentRecord. You get this compile error because you are trying to compile the two Java files that are not present in the current directory anymore.java:123) at java.ClassLoader.misc.SecureClassLoader.loadClassInternal (ClassLoader.java:235) at java.java:289) at sun.java error: cannot read: StudentRecord.ClassLoader.defineClass (URLClassLoader.loadClass (Launcher.lang.net.class del StudentRecordExample.E.java move \lab\StudentRecord.java and StudentRecordExample.java:251) at java.java \lab\studentpackage\StudentRecord. You will experience compile errors as following.D. Compile code.java 880 318 .Launcher$AppClassLoader. The compilation should succeed. mkdir \lab\studentpackage move \lab\StudentRecordExample. Create a new directory called studentpackage and then move StudentRecord.java:539) at java.java studentpackage\StudentRecordExample.class C:\lab>javac StudentRecord.URLClassLoader.J. del StudentRecord.java 1 error 7.java:302) 5.java:274) at java.security.
You will experience NoClassDefFoundError because it is trying to find the class in the current directory instead of in the studentpackage directory.E. C:\lab>java studentpackage.java:194) at java.415.java:302) Introduction to Programming I 319 .856.lang.URLClassLoader$1.loadClass (Launcher.ClassLoader.lang. Run the code with propert package structure.access$100 (URLClassLoader.loadClassInternal (ClassLoader.misc.defineClass (ClassLoader.lang.defineClass (SecureClassLoader.I StudentRecordExample.java:289) at sun. It should work this time.J.lang.loadClass (ClassLoader.net.java:251) at java.loadClass (ClassLoader. It is because it is still looking for studentpackage/StudentRecordExample.URLClassLoader.defineClass (URLClassLoader.java:55) at java.ClassLoader. C:\lab>cd studentpackage C:\lab\studentpackage>java StudentRecordExample Exception in thread "main" java.Launcher$AppClassLoader. Run the code as follows.ClassLoader. And the following is what you will experience.net.ClassLoader.security.defineClass0(Native Method) at java. C:\lab>java StudentRecordExample Exception in thread "main" java.lang.ClassLoader.lang.class in the currently directory and it could not find it.java:187) at java.NoClassDefFoundError: StudentRecordExample 9.URLClassLoader.D.NoClassDefFoundError: StudentRecordExample (wrong name: studentpackage/StudentRecordExample) at java.net.java:539) at java.URLClassLoader.run (URLClassLoader.java:123) at java.class 07/06/2005 12:17 PM 690 StudentRecordExample.494 bytes 2 Dir(s) 1.128 bytes free 8.doPrivileged(Native Method) at java.findClass (URLClassLoader. Now you thught you should be able to run the application under the studentpackage directory itself so you go into the directory and run the code.AccessController.lang.java:235) at java.SecureClassLoader.security.java:274) at java.java 4 File(s) 4.net.StudentRecordExample Anna Count=0 10.
J.E.StudentRecordExample Anna Count=0 Creating your own: 1.fruitpackage Add a couple of methods of your own 2.java should have the following package statement at the top • package foodpackage.I 11.NoClassDefFoundError: StudentRecordExample C:\lab\studentpackage>java -classpath \lab studentpackage.lang. Create a class called Food under foodpackage. Create a class called FoodMain under foodpackage. Compile and run the code Introduction to Programming I 320 .fruitpackage package • • FoodMain class creates an Food object FoodMain class then calls a method of Food object 3. Now there is a way you can specify the classpath using -classpath command line option as following: C:\lab\studentpackage>java -classpath \lab StudentRecordExample Exception in thread "main" java.D.fruitpackage pacakge • • Food.
println("Inside Person:Constructor 2 receiving two parameters: " + name + ".I Chapter 11 Hands-on 11. this.println("Inside Person:Constructor").E.address = address.java package personpackage. } public void setAddress(String s){ address = s.1 Inheritance – Constructor 1. } public void setName(String s){ name = s. } public String getAddress(){ return address. } public String getName(){ System.println("Person: getName()"). } } Introduction to Programming I 321 . } public Person (String name.D. public class Person { private String name.J.out. this.out. Write Person. private String address. String address){ System.out. " + address).name = name. public Person(){ System. return name.
java java personpackage. public String getHobby(){ return hobby. Compile and run the code using a directory structure. } public void setHobby(String s){ hobby = s. cd \lab javac personpackage\*. Write Student. public class Student extends Person { private String hobby. } } 4.java package personpackage.I 2. } } } 3.D.Main 5. Verify the result is as following C:\lab>java personpackage. Write Main. public class Main { public static void main(String [] args ){ Student student1 =new Student().out. public Student(){ System.Main Inside Person:Constructor Inside Student:Constructor Introduction to Programming I 322 .E.java package personpackage.J.println("Inside Student:Constructor").
Main 8. Verify the result is as following C:\lab>java personpackage. System. Modify the Student.java java personpackage. cd \lab javac personpackage\*.println("Inside Student:Constructor"). public String getHobby(){ return hobby. Compile and run the code using a directory structure. } } } 7.Main Inside Person:Constructor 2 receiving two parameters: Sang. "1 Dreamland"). package personpackage.I 6. 1 Dreamland Inside Student:Constructor Introduction to Programming I 323 .E.J. } public void setHobby(String s){ hobby = s. public Student(){ super("Sang".D. The code fragment that needs to be added is in bold characters.java as following.out. public class Student extends Person { private String hobby.
java • • Right personpackage package node (not PersonPackage project node) and select New->Java Class Under Name and Location pane.java 6.I Using Netbeans: 1.java 4. Create Person. Right click personpackage package node (not PersonPackage project node) and select Compile Package (F9) 9.J.D. Create Student. Replace the code in the NetBeans generated Main. Replaced the code in the NetBeans generated Person. Replaced the code in the NetBeans generated Student. (Figure-10 below) • For Project Name field. • for Class Name field. Create a new NetBeans project and Main. Right click Main select Run File 10.1 desktop icon Solaris/Linux: <NETBEANS41_HOME>/bin/netbeans 2.java 8. Start the NetBeans IDE 4. Under Choose Project. • for Class Name field.java main class • • • • Select File from the menu bar and select New Project. type Student • Click Finish 7.1 > NetBeans IDE or click NetBeans IDE 4. Under Name and Location pane.Modify the Student.java • Right personpackage node (not PersonPackage project node) and select New>Java Class • Under Name and Location pane.java. fill it with PersonPackage • Click Finish 3. select General and Java Application Click Next. Right click Main select Run File Introduction to Programming I 324 . 11. Right click personpackage pacakge node (not PersonPackage project node) and select Compile Package (F9) 12. type Person • Click Finish 5.E.1 (if you have not done so yet) • • Windows: Start > All Programs > NetBeans 4.
J. Student student3 =new TuftsStudent(). You should see the following: Inside Inside Inside Inside Inside Inside Inside Inside Person:Constructor Student:Constructor Person:Constructor Student:Constructor TuftsStudent:Constructor Person:Constructor Student:Constructor TuftsStudent:Constructor Introduction to Programming I 325 . Write TuftsStudent.java to create an instance of TuftsStudent class as following TuftsStudent student2 =new TuftsStudent().println("Inside TuftsStudent:Constructor"). 3.out.E. Compile and run the code.I Creating your own: 1. } 2. Modify the Main.java as following • • TuftsStudent class extends Student class Write a constructor of the TuftsStudent class as following public TuftsStudent(){ System.D.
out.Overriding 1. package personpackage.setName("Sang").J.Main Inside Person:Constructor Inside Student:Constructor Person: getName() Calling getName() method: name is Sang Introduction to Programming I 326 .D.2 Inheritance . Compile and run the code using a directory structure.Main 3. public class Main { public static void main(String [] args ){ Student student1 =new Student(). The code fragment that needs to be added is in bold characters. System. } } 2.getName()).java as following. which is a parent class of Student class student1.println("Calling getName() method: name is " + student1.I 11.java java personpackage. Verify the result is as following C:\lab>java personpackage. Modify Main. // Calling methods defined in Person class. cd \lab javac personpackage\*.E.
out.out. public class Student extends Person { private String hobby. } // Override getName() method of the parent class public String getName(){ System. Verify the result is as following C:\lab>java personpackage. The code fragment that needs to be added is in bold characters. return "Passionate" + super.java as following. package personpackage. cd \lab javac personpackage\*. Compile and run the code using a directory structure.E.I 5. } public void setHobby(String s){ hobby = s.Main Inside Person:Constructor Inside Student:Constructor Student: getName() Person: getName() Calling getName() method: name is PassionateSang Introduction to Programming I 327 . public String getHobby(){ return hobby.getName(). } } } 6.java java personpackage.D.Main 7.println("Student: getName()").println("Inside Student:Constructor").J. Modify the Student. public Student(){ System.
Change Main.getHobby().out.J. Inside Inside Inside Inside Inside Inside Person:Constructor Student:Constructor Person:Constructor Student:Constructor TuftsStudent:Constructor Person:Constructor 328 Introduction to Programming I . You should see the following result. // set hobbies of student2 and student3 student2. System.setHobby("dancing"). Right click personpackage pacakge node (not PersonPackage project node) and select Compile Package (F9) 6. Right click Main select Run File 4. // get hobbies of student2 and student3 String hobby2 = student2.println("Hobby of student2 " + hobby2).getHobby(). } 2. Right click Main select Run File Creating your own: 1. } public void setHobby(String s){ System. Modify the Student. Compile and run the code. String hobby3 = student3.I Using NetBeans: It is assumed you are using the same NetBeans project you are using the same NetBeans project you created in Chapter 10. Right click personpackage package node (not PersonPackage project node) and select Compile Package (F9) 3.java to invoke setHobby() and getHobby() methods of the newly created TuftsStudent object instances as follows. Modify the Main.out. student3.E. super.getHobby(). 2. In your TuftsStudent class.D.setHobby("swimming"). System.println("Inside TuftsStudent:setHobby() method").out.java.println("Inside TuftsStudent:getHobby() method").out. 1. return "My hobby is " + super. override getHobby() and setHobby() methods of the Student class as follows public String getHobby(){ System.println("Hobby of student3 " + hobby3).java 5.setHobby(s). 3.
I Inside Student:Constructor Inside TuftsStudent:Constructor Inside TuftsStudent:setHobby() method Inside TuftsStudent:setHobby() method Inside TuftsStudent:getHobby() method Hobby of student2 My hobby is swimming Inside TuftsStudent:getHobby() method Hobby of student3 My hobby is dancing Introduction to Programming I 329 .D.J.E.
} } Introduction to Programming I 330 . This is the same Person. private String address.E. } public void setAddress(String s){ address = s.println("Inside Person:Constructor"). return name.println("Inside Person:Constructor 2 receiving two parameters: " + name + ". public class Person { private String name. this.name = name.out.I 11.address = address. Write Person. this. } public String getName(){ System.java as in the previous exercise except the package name.println("Person: getName()").out.J. } public void setName(String s){ name = s.D. } public String getAddress(){ return address. public Person(){ System.3 Polymorphism 1.java. package polypackage. which you will write in the subsequent steps. String address){ System. } public Person (String name. Person class is a parent class of both Student and Employee classes.out. " + address).
" + address). package polypackage. Student class is a subclass of a Person class.out.getName(). address). String address){ super(name.J.I 2.println("Inside Student:Constructor 2 receiving two parameters: " + name + ".out.E.D. System.out. } public void setHobby(String s){ hobby = s. } } Introduction to Programming I 331 .println("Inside Student:Constructor"). } // Override getName() method of the parent class public String getName(){ System. } public Student (String name.java. } public String getHobby(){ return hobby. return "Passionate Student " + super. public class Student extends Person { private String hobby. public Student(){ System.println("Student: getName()"). Write Student.
String address){ super(name.D. return "Not so Passionate Employee " + super.println("Inside Employee:Constructor 2 receiving two parameters: " + name + ". public class Employee extends Person { private String hobby. address).J.E. } public void setHobby(String s){ hobby = s. Employee class is subclass of Person class. Write Employee.getName } (). package polypackage. public Employee(){ System. System.out.out.out.java. } Introduction to Programming I 332 . } public String getHobby(){ return hobby. } // Override getName() method of the parent class public String getName(){ System.println("Inside Employee:Constructor").println("Employee: getName()"). } public Employee(String name. " + address).I 3.
Employee employeeObject = new Employee("Young".java java polypackage. Note that depending on what object type the ref variable refers to.D. Verify the result is as following. "1 Dreamland"). //Person ref.java C:\lab>java polypackage. System. Compile and run the code using a directory structure.J.Main Inside Person:Constructor 2 receiving two parameters: Sang.Main 6. } } 5.getName(). System.I 4. points to an Employee object //getName of Employee class is called String temp2 = ref. 2 Dreamland Inside Employee:Constructor 2 receiving two parameters: Young. System. C:\lab>javac polypackage\*.E.out.java package polypackage. Student studentObject = new Student("Sang". Employee type or Student type. ref = employeeObject. cd \lab javac polypackage\*.out. "2 Dreamland"). points to a Student //getName of Student class is called String temp1=ref. public class Main { public static void main( String[] args ) { Person ref. proper method gets invoked. object ref = studentObject. Write Main. 1 Dreamland Inside Student:Constructor 2 receiving two parameters: Sang. 1 Dreamland Inside Person:Constructor 2 receiving two parameters: Young. //Person ref.getName().out.println( "temp1 -" + temp1 + "\n" ).println("\n").println( "temp2 -" + temp2 + "\n" ). 2 Dreamland Student: getName() Person: getName() temp1 -Passionate Student Sang Employee: getName() Person: getName() temp2 -Not so Passionate Employee Young Introduction to Programming I 333 .
E.D.I Introduction to Programming I 334 .J.
Replace the code in the NetBeans generated Main.java • • Right polypackage node (not PolyPackage project node) and select New->Java Class Under Name and Location pane. Under Name and Location pane. Create Employee. select General and Java Application Click Next.1 > NetBeans IDE or click NetBeans IDE 4. (Figure-10 below) • For Project Name field. type Student • Click Finish 7. fill it with PolyPackage • Click Finish 3.1 (if you have not done so yet) • • Windows: Start > All Programs > NetBeans 4.java • • Right polypackage node (not PolyPackage project node) and select New->Java Class Under Name and Location pane. Create Student. Start the NetBeans IDE 4.1 desktop icon Solaris/Linux: <NETBEANS41_HOME>/bin/netbeans 2. • for Class Name field.D. type Person • Click Finish 5.java 8. Create a new NetBeans project and Main. Under Choose Project. Create Person. • for Class Name field. type Employee • Click Finish Introduction to Programming I 335 .E.I Using NetBeans: 1. • for Class Name field.java 4.java • • Right polypackage package node (not PolyPackage project node) and select New->Java Class Under Name and Location pane. Replaced the code in the NetBeans generated Student.J.java main class • • • • Select File from the menu bar and select New Project. Replaced the code in the NetBeans generated Person.java 6.
Right click polypackage pacakge node (not PolyPackage project node) and select Compile Package (F9) 14.out.Modify the Student.Main Inside Person:Constructor 2 receiving two parameters: Sang. Right click Main select Run File Creating your own: 1. C:\lab>java polypackage.println("Teacher: getName()"). Right click Main select Run File 12.java 13.java in which.java as following • • Teacher class extends Person class Teacher clsss also has the following method // Override getName() method of the parent class public String getName(){ System. 2 Dreamland Inside Employee:Constructor 2 receiving two parameters: Young. 1 Dreamland Inside Student:Constructor 2 receiving two parameters: Sang. 1 Dreamland Inside Person:Constructor 2 receiving two parameters: Young. return "Maybe Passionate Teacher" + super.getName().E. Modify the Main.D. 2 Dreamland Inside Person:Constructor 2 receiving two parameters: Wende.java 10. Replaced the code in the NetBeans generated Employee. Compile and run the code.J. You should see the following result. } 2. 21 New York Inside Teacher:Constructor 2 receiving two parameters: Wende.I 9. getName() method of the Teacher object gets called 3. Create another class called Teacher. 21 New York Student: getName() Person: getName() Passionate Student Sang temp1 -Passionate Student Sang Employee: getName() Person: getName() Not so Passionate Employee Young temp2 -Not so Passionate Employee Young Teacher: getName() Person: getName() temp3 -Maybe Passionate Teacher Wende Introduction to Programming I 336 . Right click polypackage package node (not PolyPackage project node) and select Compile Package (F9) 11.
Write Main. Note that you will experience a compile error since you cannot create an object instance from an abstract class.. Compile Livingthing. cd \lab javac abstractexercise\LivingThing.java package abstractexercise..java abstractexercise\Main.println("Living Thing breathing.java abstractexercise\Main.out..out. } 2..java and Main.").java. } public void eat(){ System.I 11. C:\lab>javac abstractexercise\LivingThing.D.E."). } /** * abstract method walk * We want this method to be overridden by subclasses of * LivingThing */ public abstract void walk().4 Abstract Classes 1. cannot be instantiated LivingThing x = new LivingThing(). Write abstract class called LivingThing.J.java abstractexercise\Main.LivingThing is abstract. public class Main { public static void main( String[] args ) { LivingThing x = new LivingThing().println("Living Thing eating. package abstractexercise. ^ 1 error Introduction to Programming I 337 .java. public abstract class LivingThing { public void breath(){ System.java:5: abstractexercise. } } 3.java 4.
Creating your own: 1.println("Human walks.. 2.java so that it calls dance(ds) method Introduction to Programming I 338 .java java abstractexercise.. package abstractexercise. } 3. Verify the result is as following. y.Main 8." + ds). Modify the Main.J.java that implements the dance() abstract method.java that extends the abstract LivingThing class package abstractexercise..out.I 5. Rewrite Main. Implement a concrete method in the Human.walk().java. C:\lab>java abstractexercise. Compile and run the code using a directory structure. public void dance(String ds){ System.. } } 7. cd \lab javac abstractexercise\*. } } 6. Human walks..walk().D. public class Human extends LivingThing { public void walk(){ System. Define another abstract method in the LivingThing.").java as following public abstract void dance(String dancingStyle). LivingThing y = new Human(). public class Main { public static void main( String[] args ) { Human x = new Human(). x. Write a concrete class called Human..println("Human dances..E.out.Main Human walks..
I 4. C:\lab>java abstractexercise..D.J. Compile and run the code.E.Main Human walks.. Human dances in Saturday Night Live Introduction to Programming I 339 .. You should see the following result.. Human dances in Swing Human walks.
cd \lab javac interfaceexercise\Relation.java interfaceexercise\Main.java and Main.java. Note that you will experience a compile error since you cannot create an object instance from an Interface. public class Main { public static void main( String[] args ) { Relation x = new Relation(). public boolean isEqual( Object a. cannot be instantiated Relation x = new Relation(). Write Relation.java 4. Object b).java which is an Interface.java:5: interfaceexercise. Compile Relation. } } 3.D. package interfaceexercise.J.java.java interfaceexercise\Main. public interface Relation { public boolean isGreater( Object a. ^ 1 error Introduction to Programming I 340 .E. package interfaceexercise. Object b). Object b).5 Interfaces 1 1. public boolean isLess( Object a. Write Main. C:\lab>javac interfaceexercise\Relation.Relation is abstract.I 11.java interfaceexercise\Main. } 2.
sqrt( (x2-x1)*(x2-x1) + (y2-y1)* (y2-y1) ). return (aLen == bLen). package interfaceexercise.getLength(). Object b){ double aLen = ((Line)a). return (aLen > bLen).getLength().double x2.I 5.E. } public boolean isLess( Object a. Write a concrete class that implements Relation.x2 = x2. Object b){ double aLen = ((Line)a).D. private double x2.x1 = x1.getLength(). return length.getLength(). } public boolean isGreater( Object a. this.double y2){ this. this. public class Line implements Relation { private double x1. public Line(double x1. private double y1. return (aLen < bLen). } } Introduction to Programming I 341 . this. double bLen = ((Line)b). private double y2. double bLen = ((Line)b).getLength().y2 = y2.double y1.y1 = y1. Object b){ double aLen = ((Line)a). } public double getLength(){ double length = Math. double bLen = ((Line)b). } public boolean isEqual( Object a.J.getLength().
out. 2.Main line1 is greater than line2: false line1 is equal with line2: true line1 is equal with line3: false Length of line1 is 1.java.out.4142135623730951 Length of line3 is 5.out. 1. 1. 5.0.println("Length of line1 is " + line1. b1). System. System.0.4142135623730951 Length of line2 is 1.0.0. System. 5. boolean b1 = line1. 2. 3.0.getLength()).println("line1 is greater than line2: " + boolean b2 = line1. b2).out.println("Length of line2 is " + line2. boolean b3 = line3. Rewrite Main.0).E.println("line1 is equal with line3: " + b3). System.0.I 6.isEqual(line1. 3. 2. line2).Main 8.D.println("line1 is equal with line2: " + Line line3 = new Line(1.J.0. package interfaceexercise.0.isEqual(line1. System. Verify the result as following: C:\lab>java interfaceexercise. = new Line(2. line3).getLength()). Compile and run the code using a directory structure.out.isGreater(line1. cd \lab javac interfaceexercise\*.656854249492381 Introduction to Programming I 342 .java java interfaceexercise. } } 7. System.0).0).out.println("Length of line3 is " + line3.getLength()).0. line2). public class Main { public static void main( String[] args ) { Line line1 Line line2 = new Line(1.
D.Main line1 is greater than line2: false line1 is equal with line2: true line1 is equal with line3: false Length of line1 is 1. You should see the following result • • C:\lab>java interfaceexercise.4142135623730951 Length of line3 is 5.656854249492381 1 is greater than 5 false 1 is equal with 5 false 1 is less than 5 true Introduction to Programming I 343 .E. 2.4142135623730951 Length of line2 is 1. 3. Modify Main class that compares two int type numbers.I Creating your own: 1. Create another implementation class called NumberComparison that implements Relation interface.J.
} 2. this. Write PersonInterface.out.I 11.out. public interface PersonInterface { public public public public String getName(). } } Introduction to Programming I 344 .name = name.println("Inside PersonImpl:Constructor"). } public void setAddress(String s){ address = s. public class PersonImpl implements PersonInterface { private String name.D. String getAddress(). } public String getAddress(){ return address. } public String getName(){ System.println("Inside PersonImpl:Constructor 2 receiving two parameters: " + name + ".6 Interfaces 2 1. public PersonImpl(){ System.address = address. void setName(String s). } public void setName(String s){ name = s. void setAddress(String s). } public PersonImpl (String name. this. String address){ System.println("PersonImpl: getName()").java which is an Interface.J. Write PersonImpl. package interfaceexercise2. " + address).out. package interfaceexercise2.java. private String address.E. return name. PersonImpl class implements PersonInterface Interface.
public interface StudentInterface extends PersonInterface { public String getHobby().out.java and PersonImpl. Compile PersonInterface. Write StudentInteface. package interfaceexercise2. Write StudentImpl. public class StudentImpl implements StudentInterface { private String hobby.D.println("StudentImpl: getHobby()"). } } Introduction to Programming I 345 . } public void setHobby(String s){ hobby = s. return hobby.java 4.java interfaceexercise2\PersonImpl.java. package interfaceexercise2. The StudentInteface interface extends PersonInterface interface. } 5. public void setHobby(String s).out. public StudentImpl(){ System.I 3.println("Inside StudentImpl:Constructor").java. cd \lab javac interfaceexercise2\PersonInterface. } public String getHobby(){ System.J.E.java.
} public String getHobby(){ System.java. javac interfaceexercise2\StudentInterface.java and StudentImpl.String) in interfaceexercise2.java.java:3: interfaceexercise2.java Introduction to Programming I 346 . Compilation should succeed.PersonInterface public class StudentImpl implements StudentInterface{ ^ 1 error 7.java interfaceexercise2\StudentImpl.D. return hobby.J.I 6. You will experience the compile error.out.java interfaceexercise2\StudentImpl. public class StudentImpl extends PersonImpl implements StudentInterface { private String hobby. } public void setHobby(String s){ hobby = s. This is because StudentImpl.println("StudentImpl: getHobby()").lang. Compile Studentnterface.java and StudentImpl. Modify StudentImpl.E. C:\lab>javac interfaceexercise2\StudentInterface.java.StudentImpl is not abstract and does not override abstract method setAddress(java. The code fragment that needs to be added is highlighted in bold font. public StudentImpl(){ System.java interfaceexercise2\StudentImpl. Compile Studentnterface.out.java did not implement all the abstract methods defined in both StudentInterface and PersonInteface interfaces. package interfaceexercise2.println("Inside StudentImpl:Constructor"). } } 8.
setName("Ann"). public class Main { public static void main(String [] args ){ StudentInterface student1 = new StudentImpl().out. Compile all the source code and run it. student1.I 9. Write Main.println("student1's hobby is " + s2).java java interfaceexercise2. String s1 = student1. String s2 = student1.Main 11.getName().J.getHobby().E.java. System.Main Inside PersonImpl:Constructor Inside StudentImpl:Constructor PersonImpl: getName() student1's name is Ann StudentImpl: getHobby() student1's hobby is Dancing Introduction to Programming I 347 . package interfaceexercise2.setHobby("Dancing").out. } } 10. javac interfaceexercise2\*. Verify the result is as following C:\lab>java interfaceexercise2.println("student1's name is " + s1). student1. System.D.
Write TuftsStudentImpl class. 3. int y). that it calls add and multiply methods of the 4. It should also "extend" StudentImpl class. Modify the Main. You should see the result something like following: C:\lab>java interfaceexercise2.D. public int add(int x.Main Inside PersonImpl:Constructor Inside StudentImpl:Constructor PersonImpl: getName() student1's name is Ann StudentImpl: getHobby() student1's hobby is Dancing Inside PersonImpl:Constructor Inside StudentImpl:Constructor PersonImpl: getName() tuftsstudent1's name is Mario StudentImpl: getHobby() tuftsstudent1's hobby is Tennis StudentImpl: add() tuftsstudent1's addition is 11 StudentImpl: multiply() tuftsstudent1's multiplication is 311.J. public double multiply(double p. Define the following new methods inside the TuftsStudentInterface interface. It should "extend" StudentInterface inteface. Write TuftsStudentInterface inteface. It "implements" TuftsStudentInterface.2 Introduction to Programming I 348 .I Creating your own: 1.java so TuftsStudentInterface interface. 2. double q).E.
} } } 2. Verify the result C:\lab>java exceptionexercise.java java exceptionexercise. } catch( ArrayIndexOutOfBoundsException exp ){ System. Write ExceptionExample.E. Compile and run the code using a directory structure. cd \lab javac exceptionexercise\*.ExceptionExample 3.out.J.out.println("Exception caught!").1 Exception Handling 1. public class ExceptionExample { public static void main( String[] args ){ try{ System.java package exceptionexercise.D.I Chapter 12 Hands-on 12.println( args[1] ).ExceptionExample Exception caught! Introduction to Programming I 349 .
getName()). StudentRecord myOwnRecord =new StudentRecord().setName("myOwn").increaseStudentCount(). //set the name of the students annaRecord.setName("Anna"). System.I Answers to Hands-on Exercises 10. StudentRecord.println("Average of my Own="+myOwnRecord. myOwnRecord.out.setEnglishGrade(90.setName("Cris").setName("Beah").increaseStudentCount().2). crisRecord. } } Introduction to Programming I 350 .setMathGrade(60.out.2).println(annaRecord. StudentRecord.E. StudentRecord beahRecord =new StudentRecord(). myOwnRecord.out.D.println(myOwnRecord.println ("Count="+StudentRecord.increaseStudentCount(). System.getAverage()).J. beahRecord. StudentRecord.increaseStudentCount().getName()).getStudentCount()).1 Create your own class StudentRecoredExample. StudentRecord. myOwnRecord. //print number of students System.out. //set grades myOwnRecord.setScienceGrade(70. StudentRecord crisRecord =new StudentRecord(). //print anna's name System.2).java public class StudentRecordExample{ public static void main(String [] args ){ //create three objects for Student record StudentRecord annaRecord =new StudentRecord().
private double average. result =(mathGrade+englishGrade+scienceGrade )/3. } /** *Changes the name of the student */ public void setName(String temp ){ name =temp. } /** *returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount. return result.I StudentRecord. } /** *Computes the average of the english. // static variables private static int studentCount = 0. private double mathGrade. } public void setScienceGrade(double grade){ scienceGrade = grade.java public class StudentRecord { // instance variables private String name.J. private double scienceGrade.math and science *grades */ public double getAverage(){ double result =0. private double englishGrade. } public void setEnglishGrade(double grade){ englishGrade = grade. } public void setMathGrade(double grade){ mathGrade = grade.E. } } Introduction to Programming I 351 . /** *Returns the name of the student */ public String getName(){ return name. } public static void increaseStudentCount(){ studentCount++.D.
} /** *Changes the name of the student */ public void setName(String temp ){ name =temp.math and science *grades */ public double getAverage(){ double result =0. private double average. // static variables private static int studentCount = 0.I 10. private double mathGrade.J. result =(mathGrade+englishGrade+scienceGrade )/3. } public void setEnglishGrade(double grade){ englishGrade = grade. private double englishGrade. /** *Returns the name of the student */ public String getName(){ return name. } public static void increaseStudentCount(){ studentCount++. private double scienceGrade. } public void setMathGrade(double grade){ mathGrade = grade.E.D. } public void setScienceGrade(double grade){ scienceGrade = grade. return result.java public class StudentRecord { // instance variables private String name.2 Overloading StudentRecord. } Introduction to Programming I 352 . } /** *returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount. } /** *Computes the average of the english.
D. double averageGrade. int studentCount){ System.setName("Anna"). annaRecord.out. } } Introduction to Programming I 353 .print("Name:"+name+" "). annaRecord.out. //overloaded methods annaRecord.println("Student count:"+studentCount). annaRecord.getName()). annaRecord. } public void print(String name.J.out.java public class StudentRecordExample2{ public static void main(String [] args) { StudentRecord annaRecord =new StudentRecord().E.getName().print(annaRecord. System.setScienceGrade(100). annaRecord.print(annaRecord. System. } public void print(String name. System.print(annaRecord.getStudentCount()).I public void print(String name ){ System. double averageGrade){ System.5). annaRecord.println("Average Grade:"+averageGrade).println("Average Grade:"+averageGrade). } } StudentExample2.out.getAverage(). annaRecord.out.getName().setEnglishGrade(95.getAverage()).print("Name:"+name+" "). annaRecord.println("Name:"+name).out.
J. public class Food { //instance variables private String color = "white".E. Create Food.java under a proper directory structure FoodMain. public String getColor(){ return color.getColor } ()).fruitpackage.FoodMain 4.fruitpackage.java under a proper directory structure cd \lab mkdir foodpackage mkdir foodpackage\fruitpackage jedit foodpackage\fruitpackage\Food.java package foodpackage.out.3 Packaging 1.fruitpackage.D. public class FoodMain{ public static void main(String [] args ){ Food food1 =new Food().fruitpackage.println("Color of the food ="+food1. Create FoodMain.I 10. } 3. } } 2.java java foodpackage.java package foodpackage. Verify the result C:\lab>java foodpackage. System.FoodMain Color of the food =white Introduction to Programming I 354 .java Food. Compile and run the code cd \lab javac foodpackage\fruitpackage\*.
java public class Main { public static void main(String [] args ){ Student student1 =new Student(). TuftsStudent student2 =new TuftsStudent(). } public String getHobby(){ System.D. return "My hobby is " + super.setHobby(s).println("Inside TuftsStudent:setHobby() method"). } } 11. } } Introduction to Programming I 355 .out.out.println("Inside TuftsStudent:Constructor").java package personpackage.out.java public class TuftsStudent extends Student{ /** Creates a new instance of TuftsStudent */ public TuftsStudent() { System.J.2 Inheritance .E.out.println("Inside TuftsStudent:getHobby() method").Overriding TuftsStudent. /** * * @author sang */ public class TuftsStudent extends Student{ /** Creates a new instance of TuftsStudent */ public TuftsStudent() { System. } } Main. super. Student student3 =new TuftsStudent().1 Inheritance – Constructor TuftsStudent.I 11.getHobby(). } public void setHobby(String s){ System.println("Inside TuftsStudent:Constructor").
out.setHobby("dancing").setHobby("swimming"). Student student3 =new TuftsStudent().I Main. System.D. TuftsStudent student2 =new TuftsStudent().E. String hobby3 = student3. // get hobbies of student2 and student3 String hobby2 = student2. // set hobbies of student2 and student3 student2.J.getHobby(). student3. System.java package personpackage.println("Hobby of student3 " + hobby3). public class Main { public static void main(String [] args ){ Student student1 =new Student(). } } Introduction to Programming I 356 .println("Hobby of student2 " + hobby2).getHobby().out.
out.J. System.out.I 11.println("\n").java package polypackage. Employee employeeObject = new Employee("Young".println( "temp1 -" + temp1 + "\n" ). } public Teacher(String name. " + address).out. public Teacher(){ System. points to a // Student object //getName of Student class is called String temp1=ref.D. "1 Dreamland"). public class Main { public static void main( String[] args ) { Person ref. points to an // Employee object Introduction to Programming I 357 . "21 New York").println("Teacher: getName()").E.println("Inside Teacher:Constructor").out.getName(). Student studentObject = new Student("Sang". } // Override getName() method of the parent class public String getName(){ System. Teacher teacherObject = new Teacher("Wende". String address){ super(name. //Person ref. System. "2 Dreamland").out.println("Inside Teacher:Constructor 2 receiving two parameters: " + name + ". ref = studentObject.out. public class Teacher extends Person { private String hobby. return "Maybe Passionate Teacher " + super.java package polypackage. ref = employeeObject.3 Polymorphism Teacher. address). } } Main. //Person ref.println( temp1 ). System. System.getName(). } public String getHobby(){ return hobby. } public void setHobby(String s){ hobby = s.
} public void eat(){ System. points to an // Teacher object //getName of Employee class is called String temp3 = ref..println( "temp2 -" + temp2 + "\n" ).getName(). } Introduction to Programming I 358 .getName().D.println( temp2 ).java package abstractexercise. System. } } 11.println( "temp3 -" + temp3 + "\n" ).J."). public abstract class LivingThing { public void breath(){ System. } /** * abstract method walk * We want this method to be overridden by subclasses of * LivingThing */ public abstract void walk()..4 Abstract Classes LivingThing. ref = teacherObject.. /** * abstract method dance * We want this method to be overridden by subclasses of * LivingThing */ public abstract void dance(String dancingStyle).out.out.println("Living Thing breathing. //Person ref. System..out.I //getName of Employee class is called String temp2 = ref.E.out.out. System.println("Living Thing eating.").
x.").walk().dance("Saturday Night Live").out. } } Introduction to Programming I 359 .J.E. y.I Human. LivingThing y = new Human(). y.walk().. } } Main.java package abstractexercise.dance("Swing"). public class Human extends LivingThing { public void walk(){ System.println("Human walks. public class Main { public static void main( String[] args ) { Human x = new Human().out.D. x.. } public void dance(String ds){ System.java package abstractexercise.println("Human dances in " + ds).
intValue() > bi. 3. line2).println("line1 is equal with line3: " + b3). Integer bi = (Integer)b.out. line2).D. System.isEqual(line1. Object b){ Integer ai = (Integer)a.out. boolean b3 = line3. public class Main { public static void main( String[] args ) { Line line1 Line line2 = new Line(1.out.0. Relation r1 = new NumberComparison().println(""). System. } public boolean isEqual(Object a.intValue() == bi. 2.I 11. System. 5.println("line1 is equal with line2: " + b2).println("Length of line1 is " + line1. Introduction to Programming I 360 .java package interfaceexercise. boolean b1 = line1.println("Length of line2 is " + line2.intValue()).println("line1 is greater than line2: " + boolean b2 = line1. public class NumberComparison implements Relation { public boolean isGreater(Object a. = new Line(2.0. 2.intValue()). System. Integer x = new Integer(1). Object b){ Integer ai = (Integer)a. 2. 1. System.isGreater(line1.out. } public boolean isLess(Object a. Integer bi = (Integer)b. line3). return (ai. 3.java package interfaceexercise.out.getLength()).0). Integer bi = (Integer)b.0.0. Integer y = new Integer(5).intValue() < bi. Line line3 = new Line(1.0. } } Main.5 Interfaces 1 NumberComparion.out.0. b1).J. return (ai. System.0). Object b){ Integer ai = (Integer)a. 1.getLength()).0.println("Length of line3 is " + line3.getLength()).isEqual(line1.0.E. return (ai. 5.out.0.0). System.intValue()).
+ " " + b6).E.out. System.isGreater(x.println(x + " is less than " + y + " " + b5).out. System. y). y).println(x + " is equal with " + y boolean b6 = r1.println(x + " is greater than " + y boolean b5 = r1.D.isLess(x.J. } + " " + } Introduction to Programming I 361 . System.isEqual(x.out. boolean b4 = r1. y).I b4).
println("StudentImpl: add()"). public double multiply(double p. student1. double q). System. int y).J. student1. tuftsstudent1.getHobby(). System.println("tuftsstudent1's name is " + s3). double q){ System. return x+y. Introduction to Programming I 362 .setHobby("Tennis").I 11. } TuftsStudentImpl.println("student1's hobby is " + s2). String s2 = student1. public interface TuftsStudentInterface extends StudentInterface { public int add(int x. int y){ System.setHobby("Dancing").6 Interfaces 2 TuftsStudentInterface.out. tuftsstudent1.E. public class TuftsStudentImpl extends StudentImpl implements TuftsStudentInterface { public int add(int x.println("").out.setName("Ann"). System. System. String s1 = student1.out.println("StudentImpl: multiply()").java package interfaceexercise2. String s3 = tuftsstudent1.getName(). public class Main { public static void main(String [] args ){ StudentInterface student1 = new StudentImpl().java package interfaceexercise2. } public double multiply(double p.D. TuftsStudentInterface tuftsstudent1 = new TuftsStudentImpl().java package interfaceexercise2.out.setName("Mario"). return p*q.out.getName().out.println("student1's name is " + s1). } } Main.
System. + d1).println("tuftsstudent1's addition is " + double d1 = tuftsstudent1.D.out.multiply(10.out.add(5. 6).println("tuftsstudent1's hobby is " + s4). 31.0.println("tuftsstudent1's multiplication is " i1).getHobby().I String s4 = tuftsstudent1.12).out. System.J. int i1 = tuftsstudent1. } } Introduction to Programming I 363 . System.E.
D.com/SiliconValley/Park/3230/java/javl1002. High-Level Programming Language.com/basic_flow_chart_symbols. Available at http://www. Available at http://home.Inheritance and Polymorphism.html 8.com at http://www.developer. February 2001. Java for Engineers and Scientists 2nd Edition.wikipedia. Available at http://home.webopedia. Available at http://java.Gary B.org/wiki/High-level_programming_language 5. Available at http://java.sun.html 3. Java How to Program 5th Edition.answers.com/docs/books/tutorial/java/nutsandbolts/branch. From Webopedia at http://www. Sun Microsystems. Variables and Expressions.php/983081 22. 23.html 7.html 27.com/TERM/I/integrated_development_environment. Writing Abstract Classes and Methods. Defining an Interface. Java Programming Complete Concepts and Techniques.com/TERM/p/programming_language.ca/~ve3ll/jatutor7.org/wiki/Programming_language 2.com/topic/programming-language 4. Thomas J. From Answers.The Essence of OOP using Java. Available at http://www.Sun Java Programming Student Guide SL-275. 26.sun.Stephen J.htm 6.html.J.Java Branching Statements.geocities. Joy L.com/docs/books/tutorial/java/interpack/interfaceDef.htm 21. Course Technology Thomson Learning.htm.com/tech/article.Deitel & Deitel.html 9. Shelly. Cashman.com/javaworld/javaqa/2000-05/03-qa-0526-pass.cogeco.com/docs/books/tutorial/java/javaOO/abstract. Defining Flowchart Symbols. 2001. Chapman.E. From Webopedia at http://www. Integrated Development Environment.Does Java pass by reference or pass by value? Why can't you swap in Java? Available at http://www.wikipedia.webopedia. From Wikipedia at http://en. Introduction to Programming I 364 . 2004 24.Encapsulation.sun. Pearson Prentice Hall. From Wikipedia at http://en. Programming Language.javaworld.html 20.ca/~ve3ll/jatutor4. Runtime Polymorphism through Inheritance.pattonpatton.cogeco. Programming Language. 25. 28. Starks. Programming Language. Available at http://www. Available at http://java.I References 1.
Sign up to vote on this title
UsefulNot useful | __label__pos | 0.989615 |
Firebase – AppDividend https://appdividend.com Latest Code Tutorials Sun, 09 Dec 2018 14:39:17 +0000 en-US hourly 1 https://wordpress.org/?v=4.9.8 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png Firebase – AppDividend https://appdividend.com 32 32 React Native Firebase Example https://appdividend.com/2018/04/23/react-native-firebase-example-from-scratch/ https://appdividend.com/2018/04/23/react-native-firebase-example-from-scratch/#comments Mon, 23 Apr 2018 04:12:43 +0000 http://localhost/wordpress/?p=556 Firebase React Native For Beginners
React Native Firebase Example is the today’s topic. Getting started with React Native and Firebase. I was first skeptical about Firebase, but after using it, it seems like the Firebase may be able to speed up widespread mobile and web app development. In a traditional mobile or web app progress when you’re building something other. Also, you can check out the below course […]
The post React Native Firebase Example appeared first on AppDividend.
]]>
Firebase React Native For Beginners
React Native Firebase Example is the today’s topic. Getting started with React Native and Firebase. I was first skeptical about Firebase, but after using it, it seems like the Firebase may be able to speed up widespread mobile and web app development. In a traditional mobile or web app progress when you’re building something other.
Also, you can check out the below course to learn React Native From Scratch.
React Native – The Practical Guide
React Native Firebase Example
Let us start our example by installing the React Native Project.
Step 1: Install React Native.
Install the React Native CLI using the following command.
# for mac users
sudo npm install -g react-native-cli
# for windows users: open cmd on admin mode and type
npm install -g react-native-cli
Now, create our project using the following command.
react-native init RNFbase
Go into that project.
cd RNFbase
Start the package server and simulator using the following command.
react-native run-ios --simulator="iPhone X"
You will see this screen.
React Native Firebase Example
If you are facing Yellow warnings like isMounted(…) is deprecated in plain javascript react classes” error with this dependencies then add the following code inside App.js file.
// App.js
import { YellowBox } from 'react-native';
YellowBox.ignoreWarnings(['Warning: isMounted(...) is deprecated', 'Module RCTImageLoader']);
Step 2: Install Firebase Dependency.
Type the following command to install the Firebase.
yarn add firebase
# or
npm install firebase --save
Step 3: Create required directories.
In the root of the project, make the one directory called src. In that directory, create three folders.
1. screens
2. components
3. services
Screens folder contains the screens which we need to display to the User. In our case, we will create three screens.
Components folder contains the mobile components we will use to display the data from the API.
Services folder contains network files. It is the files in which we will write the code to make a request to the server and get the response from the server.
Step 4: Create two screens.
Inside src >> screens folder, create the following files.
1. Home.js
2. AddItem.js
3. ListItem.js
Home.js is the pure React Native class.
// Home.js
import React, { Component } from 'react';
import { View, Text } from 'react-native';
export default class Home extends Component {
render() {
return (
<View>
<Text>Home Screen</Text>
</View>
)
}
}
Same do for the AddItem.js file.
// AddItem.js
import React, { Component } from 'react';
import { View, Text } from 'react-native';
export default class AddItem extends Component {
render() {
return (
<View>
<Text>Add Item</Text>
</View>
)
}
}
Also, same for ListItem.js file.
// ListItem.js
import React, { Component } from 'react';
import { View, Text } from 'react-native';
export default class ListItem extends Component {
render() {
return (
<View>
<Text>List Item</Text>
</View>
)
}
}
Step 5: Integrate React Native Navigation.
We need to install React Navigation library to transition the app from one screen to another screen.
yarn add react-navigation
# or
npm install react-navigation --save
Now, after installing, go to the App.js file. We will use StackNavigator to transit from one to another screen. It is routing for our application.
// App.js
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import Home from './src/screens/Home';
import AddItem from './src/screens/AddItem';
import ListItem from './src/screens/ListItem';
import { YellowBox } from 'react-native';
YellowBox.ignoreWarnings(['Warning: isMounted(...) is deprecated', 'Module RCTImageLoader']);
const AppNavigator = StackNavigator({
HomeScreen: { screen: Home },
AddItemScreen: { screen: AddItem },
ListItemScreen: { screen: ListItem }
});
export default class App extends Component {
render() {
return (
<AppNavigator />
);
}
}
We have included both the screen here and passed that screen into the StackNavigator function. It will handle the transition of our screens. HomeScreen displays like the following.
React Native Firebase Tutorial
Step 6: Create a database in Firebase console.
Go to the https://firebase.google.com and login to your Google account and create a new project.
Now, in React Native, we fetch the database config as a web app, so go to your web app section and get the config object. We need to connect our app to the firebase.
Create a new folder, inside src folder, called config and in that, make a new file called db.js. Write the following code in it.
// db.js
import Firebase from 'firebase';
let config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
let app = Firebase.initializeApp(config);
export const db = app.database();
You have your configuration values, so you need to copy the whole config from your firebase app.
Step 7: Create a form the add the data.
Write the following code inside AddItem.js file.
// AddItem.js
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TextInput,
TouchableHighlight
} from 'react-native';
export default class AddItem extends Component {
constructor(props) {
super(props);
this.state = {
name: '',
error: false
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
this.setState({
name: e.nativeEvent.text
});
}
handleSubmit() {
console.log(this.state.name)
}
render() {
return (
<View style={styles.main}>
<Text style={styles.title}>Add Item</Text>
<TextInput
style={styles.itemInput}
onChange={this.handleChange}
/>
<TouchableHighlight
style = {styles.button}
underlayColor= "white"
onPress = {this.handleSubmit}
>
<Text
style={styles.buttonText}>
Add
</Text>
</TouchableHighlight>
</View>
)
}
}
const styles = StyleSheet.create({
main: {
flex: 1,
padding: 30,
flexDirection: 'column',
justifyContent: 'center',
backgroundColor: '#2a8ab7'
},
title: {
marginBottom: 20,
fontSize: 25,
textAlign: 'center'
},
itemInput: {
height: 50,
padding: 4,
marginRight: 5,
fontSize: 23,
borderWidth: 1,
borderColor: 'white',
borderRadius: 8,
color: 'white'
},
buttonText: {
fontSize: 18,
color: '#111',
alignSelf: 'center'
},
button: {
height: 45,
flexDirection: 'row',
backgroundColor:'white',
borderColor: 'white',
borderWidth: 1,
borderRadius: 8,
marginBottom: 10,
marginTop: 10,
alignSelf: 'stretch',
justifyContent: 'center'
}
});
So, I have defined some basic style of our form. So our AddItem.js screen looks like this.
Firebase React Native Example
Step 8: Create a service file to add data to Firebase.
Inside services folder, create one file called ItemService.js.
// ItemService.js
import { db } from '../config/db';
export const addItem = (item) => {
db.ref('/items').push({
name: item
});
}
Now, we need to import this services file into AddItem.js file.
// AddItem.js
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
TextInput,
TouchableHighlight,
AlertIOS
} from 'react-native';
import { addItem } from '../services/ItemService';
export default class AddItem extends Component {
constructor(props) {
super(props);
this.state = {
name: ''
}
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
handleChange(e) {
this.setState({
name: e.nativeEvent.text
});
}
handleSubmit() {
addItem(this.state.name);
AlertIOS.alert(
'Item saved successfully'
);
}
render() {
return (
<View style={styles.main}>
<Text style={styles.title}>Add Item</Text>
<TextInput
style={styles.itemInput}
onChange={this.handleChange}
/>
<TouchableHighlight
style = {styles.button}
underlayColor= "white"
onPress = {this.handleSubmit}
>
<Text
style={styles.buttonText}>
Add
</Text>
</TouchableHighlight>
</View>
)
}
}
const styles = StyleSheet.create({
main: {
flex: 1,
padding: 30,
flexDirection: 'column',
justifyContent: 'center',
backgroundColor: '#2a8ab7'
},
title: {
marginBottom: 20,
fontSize: 25,
textAlign: 'center'
},
itemInput: {
height: 50,
padding: 4,
marginRight: 5,
fontSize: 23,
borderWidth: 1,
borderColor: 'white',
borderRadius: 8,
color: 'white'
},
buttonText: {
fontSize: 18,
color: '#111',
alignSelf: 'center'
},
button: {
height: 45,
flexDirection: 'row',
backgroundColor:'white',
borderColor: 'white',
borderWidth: 1,
borderRadius: 8,
marginBottom: 10,
marginTop: 10,
alignSelf: 'stretch',
justifyContent: 'center'
}
});
I have imported addItem function and passed our textbox value to that function and also imported the AlertIOS component to display the alert box saying that our data has been successfully saved.
React Native Firebase save data
Also, you can see the data in the Firebase.
Firebase Tutorial
Step 9: Display Items.
Write the following code inside ListItem.js file.
// ListItem.js
import React, { Component } from 'react';
import { View, Text, StyleSheet} from 'react-native';
import ItemComponent from '../components/ItemComponent';
import { db } from '../config/db';
let itemsRef = db.ref('/items');
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
backgroundColor: '#B6A6BB',
}
})
export default class ListItem extends Component {
state = {
items: []
}
componentDidMount() {
itemsRef.on('value', (snapshot) => {
let data = snapshot.val();
let items = Object.values(data);
this.setState({items});
});
}
render() {
return (
<View style={styles.container}>
{
this.state.items.length > 0
? <ItemComponent items={this.state.items} />
: <Text>No items</Text>
}
</View>
)
}
}
Okay, now we need to create ItemComponent.js file inside src >> components folder. It will display our data from the Firebase.
// ItemComponent.js
import React, { Component } from 'react';
import { View, Text, StyleSheet} from 'react-native';
import PropTypes from 'prop-types';
const styles = StyleSheet.create({
itemsList: {
flex: 1,
flexDirection: 'column',
justifyContent: 'space-around',
},
itemtext: {
fontSize: 24,
fontWeight: 'bold',
textAlign: 'center',
}
});
export default class ItemComponent extends Component {
static propTypes = {
items: PropTypes.array.isRequired
};
render() {
return (
<View style={styles.itemsList}>
{this.props.items.map((item, index) => {
return (
<View key={index}>
<Text style={styles.itemtext}>{item.name}</Text>
</View>
)
})}
</View>
);
}
}
React Native Fetch Data
This is not pretty much design but, I just wanted you to guys see how it can connect with Firebase and we can fetch the data and display that on the Screen. That is the main moto of this Tutorial.
That is it, I know there is lots of stuff we can fix this but, we will tackle one by one in the future tutorials.
So, React Native Firebase Example Tutorial is over. Thanks for taking.
The post React Native Firebase Example appeared first on AppDividend.
]]>
https://appdividend.com/2018/04/23/react-native-firebase-example-from-scratch/feed/ 9
Vue Firebase CRUD Example https://appdividend.com/2018/04/21/vue-firebase-crud-example/ https://appdividend.com/2018/04/21/vue-firebase-crud-example/#comments Sat, 21 Apr 2018 15:04:39 +0000 http://localhost/wordpress/?p=540
Vue Firebase CRUD Example is the today’s leading topic. If you are new to both Vue and Firebase, then you can check out my another tutorial Vue Firebase Example. It will help you to up and running with Vue and Firebase and how we can connect each other. Now, let us straight to the point and get started. […]
The post Vue Firebase CRUD Example appeared first on AppDividend.
]]>
Vue Firebase CRUD Example is the today’s leading topic. If you are new to both Vue and Firebase, then you can check out my another tutorial Vue Firebase Example. It will help you to up and running with Vue and Firebase and how we can connect each other. Now, let us straight to the point and get started.
Vue Firebase CRUD Example
Our complete app looks like this.
First, install a Vue project.
Step 1: Install Vue using vue cli.
Go to the terminal and hit the following command.
npm install -g @vue/cli
or
yarn global add @vue/cli
Step 2: Install vuefire for firebase vue binding.
Okay, now create a project using the following command.
vue create vuefirebaseexample
Go into the project.
cd vuefirebaseexample
Install the vuefire library using the following command.
yarn add vuefire firebase
or
npm install vuefire firebase --save
Import vuefire inside a main.js file.
// main.js
import Vue from 'vue'
import VueFire from 'vuefire'
import App from './App.vue'
Vue.use(VueFire)
Vue.config.productionTip = false
new Vue({
render: h => h(App)
}).$mount('#app')
Step 3: Create three components.
First, include the Bootstrap 4 in our project.
yarn add bootstrap
# or
npm install bootstrap --save
Include inside App.vue file.
<style lang="css">
@import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
</style>
Inside src >> components folder, create the following three files.
1. AddItem.vue
2. EditItem.vue
3. ListItem.vue
4. Home.vue
Now, add the following code to each component. After that, we create the route for our application.
// Home.vue
<template>
<h1>Home</h1>
</template>
<script>
export default {
components: {
name: 'Home'
}
}
</script>
// AddItem.vue
<template>
<h1>Add Item</h1>
</template>
<script>
export default {
components: {
name: 'AddItem'
}
}
</script>
// EditItem.js
<template>
<h1>Edit Item</h1>
</template>
<script>
export default {
components: {
name: 'EditItem'
}
}
</script>
// ListItem.vue
<template>
<h1>List Item</h1>
</template>
<script>
export default {
components: {
name: 'ListItem'
}
}
</script>
Step 4: Install and configure the router.
Install the vue-router dependency.
yarn add vue-router
# or
npm install vue-router --save
Now, we need to configure the routes. So let us add the following code to the main.js file.
// main.js
import Vue from 'vue'
import VueFire from 'vuefire'
import VueRouter from 'vue-router'
import App from './App.vue'
import AddItem from './components/AddItem.vue'
import EditItem from './components/EditItem.vue'
import ListItem from './components/ListItem.vue'
import Home from './components/Home.vue'
Vue.use(VueFire)
Vue.use(VueRouter)
Vue.config.productionTip = false
const routes = [
{
name: 'Home',
path: '/',
component: Home
},
{
name: 'Add',
path: '/add',
component: AddItem
},
{
name: 'Edit',
path: '/edit/:id',
component: EditItem
},
{
name: 'List',
path: '/index',
component: ListItem
},
];
const router = new VueRouter({ mode: 'history', routes: routes });
new Vue({
render: h => h(App),
router
}).$mount('#app')
Also, we need to define our router output. It means that, when we change the route, we need to display that component. So add the <router-view> inside App.vue file.
// App.vue
<template>
<div id="app">
<router-view></router-view>
</div>
</template>
<script>
<style lang="css">
@import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
</style>
Save the file and start the development server using the following command.
npm run serve
Go to this URL: http://localhost:8080/index
You can see our route is working. Now, we need to style our application.
Step: 5: Add Bootstrap Navigation.
We need to modify the App.vue file to add the Bootstrap Navigation.
// App.vue
<template>
<div id="app" class="container">
<nav class="navbar navbar-expand-sm bg-light">
<ul class="navbar-nav">
<li class="nav-item">
<router-link :to="{ name: 'Home' }" class="nav-link">Home</router-link>
</li>
<li class="nav-item">
<router-link :to="{ name: 'Add' }" class="nav-link">Add Item</router-link>
</li>
<li class="nav-item">
<router-link :to="{ name: 'List' }" class="nav-link">All Item</router-link>
</li>
</ul>
</nav>
<div class="gap">
<router-view></router-view>
</div>
</div>
</template>
<style lang="css">
@import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
</style>
<style>
.gap {
margin-top: 50px;
}
</style>
<script>
export default {
name: 'app'
}
</script>
Vue Firebase crud example
Step 6: Add Routing Progress bar Indicator.
Type the following command to install nprogress. It is a library that provides us the UI component that displays the routing indicator.
yarn add nprogress
# or
npm install nprogress --save
Add its CSS inside a main.js file.
// main.js
import '../node_modules/nprogress/nprogress.css'
Now, we need to add a hook to the router object. So when we change the route, it starts the progress bar at the top and when the routing process finishes, we need to stop that progress bar from showing in the header.
// main.js
import Vue from 'vue'
import VueFire from 'vuefire'
import VueRouter from 'vue-router'
import NProgress from 'nprogress';
import App from './App.vue'
import AddItem from './components/AddItem.vue'
import EditItem from './components/EditItem.vue'
import ListItem from './components/ListItem.vue'
import Home from './components/Home.vue'
import '../node_modules/nprogress/nprogress.css'
Vue.use(VueFire)
Vue.use(VueRouter)
Vue.config.productionTip = false
const routes = [
{
name: 'Home',
path: '/',
component: Home
},
{
name: 'Add',
path: '/add',
component: AddItem
},
{
name: 'Edit',
path: '/edit/:id',
component: EditItem
},
{
name: 'List',
path: '/index',
component: ListItem
},
];
const router = new VueRouter({ mode: 'history', routes: routes });
router.beforeResolve((to, from, next) => {
if (to.name) {
NProgress.start()
}
next()
})
router.afterEach(() => {
NProgress.done()
})
new Vue({
render: h => h(App),
router
}).$mount('#app')
Now, you can see that Progress bar is running after changing the route.
Step 7: Create a form to add an Item.
Now, we need to create a basic form inside AddItem.vue.
// AddItem.vue
<template>
<div class="container">
<div class="card">
<div class="card-header">
<h3>Add Item</h3>
</div>
<div class="card-body">
<form v-on:submit.prevent="addItem">
<div class="form-group">
<label>Item Name:</label>
<input type="text" class="form-control"/>
</div>
<div class="form-group">
<label>Item Price:</label>
<input type="text" class="form-control"/>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Add Item"/>
</div>
</form>
</div>
</div>
</div>
</template>
<script>
export default {
components: {
name: 'AddItem'
}
}
</script>
So, our form looks like this.
Vue Firebase POST data
Step 8: Connect Vue to the Firebase.
Go to Firebase and login to your console account.
Create one project.
Please enable to reading and writing in test mode for our application. Otherwise, you will not be able to store any data on the firebase.
Now, after that, you need to create a database for the web application, and then you will get your configuration object like below.
let config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
Okay, now inside src folder, create one folder called config. Inside that folder, create one file called db.js.
// db.js
import Firebase from 'firebase'
let config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
let app = Firebase.initializeApp(config)
export const db = app.database()
I have created this separate file because when we need to perform any database operations, we can connect the component separately to the database directly.
Step 9: Add Items to the Firebase.
Okay, so we need to create one object that has name and price as a property and then add that object to the Firebase method to add the items to the Firebase database. We need to require the db.js file to connect our application to the Firebase.
// AddItem.vue
<template>
<div class="container">
<div class="card">
<div class="card-header">
<h3>Add Item</h3>
</div>
<div class="card-body">
<form v-on:submit.prevent="addItem">
<div class="form-group">
<label>Item Name:</label>
<input type="text" class="form-control" v-model="newItem.name"/>
</div>
<div class="form-group">
<label>Item Price:</label>
<input type="text" class="form-control" v-model="newItem.price"/>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Add Item"/>
</div>
</form>
</div>
</div>
</div>
</template>
<script>
import { db } from '../config/db';
export default {
components: {
name: 'AddItem'
},
firebase: {
items: db.ref('items')
},
data () {
return {
newItem: {
name: '',
price: ''
}
}
},
methods: {
addItem() {
this.$firebaseRefs.items.push({
name: this.newItem.name,
price: this.newItem.price
})
this.newItem.name = '';
this.newItem.price = '';
this.$router.push('/index')
}
}
}
</script>
If your database configuration is set correctly, then you can add the items to the Firebase, and you can see the alert that says that we have successfully implemented the add item functionality.
Vue Firebase app
Step 10: Display the data from Firebase.
Now, write the following code inside ListItem.vue file.
// ListItem.vue
<template>
<div>
<h1>List Item</h1>
<table class="table table-striped">
<thead>
<tr>
<th>Item Name</th>
<th>Item Price</th>
<th colspan="2">Action</th>
</tr>
</thead>
<tbody>
<tr v-for="item of items" :key="item['.key']">
<td>{{ item.name }}</td>
<td>{{ item.price }}</td>
<td>
<router-link :to="{ name: 'Edit', params: {id: item['.key']} }" class="btn btn-warning">
Edit
</router-link>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import { db } from '../config/db';
export default {
components: {
name: 'ListItem'
},
data() {
return {
items: []
}
},
firebase: {
items: db.ref('items')
}
}
</script>
vue crud app
Step 11: Update the data to the Firebase.
Now, we need to add an edit form to the EditItem.vue file.
// EditItem.vue
<template>
<div class="container">
<div class="card">
<div class="card-header">
<h3>Edit Item</h3>
</div>
<div class="card-body">
<form v-on:submit.prevent="updateItem">
<div class="form-group">
<label>Item Name:</label>
<input type="text" class="form-control" v-model="newItem.name"/>
</div>
<div class="form-group">
<label>Item Price:</label>
<input type="text" class="form-control" v-model="newItem.price" />
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Update Item"/>
</div>
</form>
</div>
</div>
</div>
</template>
<script>
import { db } from '../config/db';
export default {
components: {
name: 'EditItem'
},
firebase: {
items: db.ref('items'),
itemsObj: {
source: db.ref('items'),
asObject: true
}
},
data () {
return {
newItem: {}
}
},
created() {
let item = this.itemsObj[this.$route.params.id]
this.newItem = {
name: item.name,
price: item.price
}
},
methods: {
updateItem() {
this.$firebaseRefs.items.child(this.$route.params.id).set(this.newItem);
this.$router.push('/index')
}
}
}
</script>
In this code, first, when the component is created, we fetch the data from the key in the firebase.
Then we bind that data to the newItem object. Here, two way data binding will help is to show the data in the form.
At last, we update the item.
Step 12: Delete the data.
Finally, add the delete code inside ListItem.vue file.
// ListItem.vue
<tbody>
<tr v-for="item of items" :key="item['.key']">
<td>{{ item.name }}</td>
<td>{{ item.price }}</td>
<td>
<router-link :to="{ name: 'Edit', params: {id: item['.key']} }" class="btn btn-warning">
Edit
</router-link>
</td>
<td>
<button @click="deleteItem(item['.key'])" class="btn btn-danger">Delete</button>
</td>
</tr>
</tbody>
Now, create the deleteItem function.
// ListItem.vue
<script>
import { db } from '../config/db';
export default {
components: {
name: 'ListItem'
},
data() {
return {
items: []
}
},
firebase: {
items: db.ref('items')
},
methods: {
deleteItem(key) {
this.$firebaseRefs.items.child(key).remove();
}
}
}
</script>
So, our whole ListItem.vue file looks like this.
// ListItem.vue
<template>
<div>
<h1>List Item</h1>
<table class="table table-striped">
<thead>
<tr>
<th>Item Name</th>
<th>Item Price</th>
<th colspan="2">Action</th>
</tr>
</thead>
<tbody>
<tr v-for="item of items" :key="item['.key']">
<td>{{ item.name }}</td>
<td>{{ item.price }}</td>
<td>
<router-link :to="{ name: 'Edit', params: {id: item['.key']} }" class="btn btn-warning">
Edit
</router-link>
</td>
<td>
<button @click="deleteItem(item['.key'])" class="btn btn-danger">Delete</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>
<script>
import { db } from '../config/db';
export default {
components: {
name: 'ListItem'
},
data() {
return {
items: []
}
},
firebase: {
items: db.ref('items')
},
methods: {
deleteItem(key) {
this.$firebaseRefs.items.child(key).remove();
}
}
}
</script>
Finally, our Vue Firebase CRUD Example Tutorial is over. We have done successfully all the CRUD operations inside Vue Application.
Fork Me On Github
The post Vue Firebase CRUD Example appeared first on AppDividend.
]]>
https://appdividend.com/2018/04/21/vue-firebase-crud-example/feed/ 6
Vue Firebase Example Tutorial https://appdividend.com/2018/04/18/vue-firebase-example-tutorial/ https://appdividend.com/2018/04/18/vue-firebase-example-tutorial/#comments Wed, 18 Apr 2018 16:54:17 +0000 http://localhost/wordpress/?p=494 Vue Firebase Tutorial
Vue Firebase Example Tutorial is the today’s topic. Firebase is a mobile and web application development platform developed by Firebase, Inc. in 2011, then acquired by Google in 2014. Firebase is the mobile platform that helps you quickly establish high-quality web and mobile apps, grow your user base, and earn more money. Vue.js is an open-source JavaScript framework for building user interfaces. Integration […]
The post Vue Firebase Example Tutorial appeared first on AppDividend.
]]>
Vue Firebase Tutorial
Vue Firebase Example Tutorial is the today’s topic. Firebase is a mobile and web application development platform developed by Firebase, Inc. in 2011, then acquired by Google in 2014. Firebase is the mobile platform that helps you quickly establish high-quality web and mobile apps, grow your user base, and earn more money. Vue.js is an open-source JavaScript framework for building user interfaces. Integration into projects that use other JavaScript libraries is made easy with Vue because it is designed to be incrementally adoptable. In this tutorial, we will see how we can connect our vue application to the Firebase backend service. Let us get started.
Vue Firebase Example Tutorial
First, we need to install Vue js application in our local. So let us do that. We use Vue CLI to generate the scaffold of our application.
Step 1: Install Vue CLI.
Go to your terminal and hit the following command.
npm install -g @vue/cli
or
yarn global add @vue/cli
If you face any error, then try to run the command as an administrator.
Now, we need to generate the necessary scaffold. So type the following command. Mine project name is vuefire, but it will confuse you that is why you will create a different name like the following.
vue create vuefirebaseexample
Vue Firebase Example Tutorial
Step 2: Install vuefire for firebase vue binding.
Go into the project.
cd vuefirebaseexample
Install the vuefire library using the following command.
yarn add vuefire firebase
or
npm install vuefire firebase --save
Open the project in your editor.
code .
Step 3: Create a basic form.
First, we need to download the bootstrap 4 for basic styling. So let us do that first.
yarn add bootstrap
Now, include the bootstrap in the src >> App.vue file.
// App.vue
<style lang="css">
@import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
</style>
Okay, so that is done. Now, create a new Vue component inside src >> components folder called CoinForm.vue.
// CoinForm.vue
<template>
<div class="container">
<div class="card">
<div class="card-header">
<h3>Add Coin</h3>
</div>
<div class="card-body">
<form v-on:submit.prevent="addCoin">
<div class="form-group">
<label>Name:</label>
<input type="text" class="form-control"/>
</div>
<div class="form-group">
<label>Price:</label>
<input type="text" class="form-control"/>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Add Coin"/>
</div>
</form>
</div>
</div>
</div>
</template>
<script>
export default {
name: 'CoinForm',
}
</script>
Import this component inside App.vue file.
// App.vue
<template>
<div id="app">
<CoinForm />
</div>
</template>
<script>
import CoinForm from './components/CoinForm.vue'
export default {
name: 'app',
components: {
CoinForm
}
}
</script>
<style lang="css">
@import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
</style>
Start the development server with the following command.
npm run serve
It will open the browser at this URL: http://localhost:8080/.
Bootstrap 4 Forms
Step 4: Connect Vue to the Firebase.
Go to Firebase and login to your console account.
Create one project.
Please enable to reading and writing in test mode for our application, otherwise, you will not be able to store any data on the firebase.
Now, after that, you need to create a database for the web application, and then you will get your configuration object like below.
let config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
Of course, you have the config values based on your account. You need to copy that.
Open the main.js file and add the following code.
// main.js
import VueFire from 'vuefire'
Vue.use(VueFire)
Okay, now inside src folder, create one folder called config. Inside that folder, create one file called db.js.
// db.js
import Firebase from 'firebase'
let config = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: ""
};
let app = Firebase.initializeApp(config)
export const db = app.database()
I have created this separate file because when we need to perform any database operations, we can connect that component to the database directly.
Step 5: Add the coins to the firebase.
Now, create the method to add the coin. I have put the whole code.
// CoinForm.vue
<template>
<div class="container">
<div class="card">
<div class="card-header">
<h3>Add Coin</h3>
</div>
<div class="card-body">
<form v-on:submit.prevent="addCoin">
<div class="form-group">
<label>Name:</label>
<input type="text" class="form-control" v-model="newCoin.name"/>
</div>
<div class="form-group">
<label>Price:</label>
<input type="text" class="form-control" v-model="newCoin.price"/>
</div>
<div class="form-group">
<input type="submit" class="btn btn-primary" value="Add Coin"/>
</div>
</form>
</div>
</div>
</div>
</template>
<script>
import { db } from '../config/db';
export default {
name: 'CoinForm',
firebase: {
coins: db.ref('coins')
},
data () {
return {
newCoin: {
name: '',
price: ''
}
}
},
methods: {
addCoin() {
this.$firebaseRefs.coins.push({
name: this.newCoin.name,
price: this.newCoin.price
})
this.newCoin.name = '';
this.newCoin.price = '';
alert("Succeessfully added")
}
}
}
</script>
Imported the db from the db.js file and then created the reference of coins.
Now, after that, whatever coins, we are adding, that will store on the firebase with reference of coins.
Save the file and try to add any crypto coins.
You see that alert pops up and we can verify on the Firebase console as well.
how to add data to the firebase
So this is how you can connect and add the data to the firebase application.
In the future post, I will show you how to make Vue Firebase CRUD application.
That is it for the Vue Firebase Example Tutorial. Thanks for taking.
The post Vue Firebase Example Tutorial appeared first on AppDividend.
]]>
https://appdividend.com/2018/04/18/vue-firebase-example-tutorial/feed/ 2
Angular Firebase Tutorial With Example From Scratch https://appdividend.com/2018/01/26/angular-firebase-tutorial-example-scratch/ https://appdividend.com/2018/01/26/angular-firebase-tutorial-example-scratch/#comments Fri, 26 Jan 2018 13:38:14 +0000 http://localhost/appdividend/?p=1568 Angular Firebase Tutorial
Angular Firebase Tutorial With Example From Scratch is today’s leading topic. We will use Angular 5 as a frontend and Firebase as a backend database service. If you are new to Angular Framework, then please check out my other tutorials like Angular Dependency Injection Tutorial Example, Angular Services Tutorial With Example From Scratch and Angular 5 CRUD Tutorial Example From […]
The post Angular Firebase Tutorial With Example From Scratch appeared first on AppDividend.
]]>
Angular Firebase Tutorial
Angular Firebase Tutorial With Example From Scratch is today’s leading topic. We will use Angular 5 as a frontend and Firebase as a backend database service. If you are new to Angular Framework, then please check out my other tutorials like Angular Dependency Injection Tutorial ExampleAngular Services Tutorial With Example From Scratch and Angular 5 CRUD Tutorial Example From Scratch. We will build Stock Market Application where the user can insert and display the share price from the Firebase. It is just a skeleton that demonstrates how to do a most common operation with Angular and Firebase. Firebase used a NoSQL Database.
If you want to learn more about Angular 7 then check out this Angular 7 – The complete Guide course.
Angular Firebase Tutorial
As we know, Angular uses TypeScript Language, which is a superset of Javascript. It transpiles the TypeScript code into the Javascript code with the help of webpack. We will start by installing Angular and configure the Firebase with Angular and build the Angular Firebase Project.
Step 1: Install the Angular.
You need to set up a dev environment before you can do anything. Install Node.js® and npm if they are not already on your machine.Then install the Angular CLI globally.
npm install -g @angular/cli
Step 2. Create a new project.
Type the following command. It will create the folder structure and also install the remaining dependencies.
ng new ng5firebase
Step 3: Install Angular Firebase Module.
Hit the following command in the terminal.
npm install firebase angularfire2 --save
Step 4: Add Firebase config to environment variable.
Open /src/environments/environment.ts and add your Firebase configuration:
// environment.ts
export const environment = {
production: false,
firebase: {
apiKey: '<your-key>',
authDomain: '<your-project-authdomain>',
databaseURL: '<your-database-URL>',
projectId: '<your-project-id>',
storageBucket: '<your-storage-bucket>',
messagingSenderId: '<your-messaging-sender-id>'
}
};
Step 5: Setup @NgModule for a AngularFireModule.
Replace the following code in the app.module.ts file.
// app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { environment } from '../environments/environment';
@NgModule({
imports: [
BrowserModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireDatabaseModule
],
declarations: [ AppComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {}
Now, we have successfully configured the Firebase with an Angular application.
Step 6: Make two components of the application.
Create one directory inside src >> app folder called components.
Go to the root of the folder and in the console and hit the following command.
ng g c index
ng g c create
We have created three components. Each component will do its job. Here we are establishing the single responsibility principle for every component.
It makes a separate folder inside src >> app directory. We need to move all these three folders inside components folder.
Also, we need to change the app.module.ts file, to write the correct path of the imported components. By default, it’s an app directory.
Step 7: Routing and Navigation.
The Angular Router enables navigation from one view to the next as users perform application tasks.
First, we need to import the routing modules inside our app.module.ts file.
Configuration
When we have created the components, it’s by default path is different and now we have moved to the components, so now its path is different. So, first, we need to change that path in app.module.ts file.
Okay, now we need to configure the routes. So make one file inside app directory called router.module.ts file.
Write the following code in it.
// router.module.ts
import { RouterModule } from '@angular/router';
import { CreateComponent } from './components/create/create.component';
import { IndexComponent } from './components/index/index.component';
export const appRoutes: Routes = [
{ path: 'create',
component: CreateComponent
},
{ path: 'index',
component: IndexComponent
}
];
We have defined one array, and inside that array, we have registered the different routes with their components. Finally, we have exported it.
Now, import this object inside app.module.ts and register the module.
// app.module.ts
import { appRoutes } from './router.module';
imports: [
BrowserModule,
AngularFireModule.initializeApp(environment.firebase),
RouterModule.forRoot(appRoutes)
],
Step 8: Define the Router outlet.
In the app.component.html file, write the following code.
<div style="text-align:center">
<h1>
Welcome to {{title}}!!
</h1>
<nav>
<a routerLink="create" routerLinkActive="active">Add coins</a>
</nav>
<router-outlet></router-outlet>
</div>
Step 9: Add Bootstrap CSS.
Download the bootstrap from its original docs and paste the CSS and JS folders inside src >> assets folder.
In the src >> index.html file, add the bootstrap css file.
<link rel="stylesheet" href="assets/css/bootstrap.min.css">
Also, change the app.component.html outlook due to bootstrap classes.
<nav class="navbar navbar-default">
<div class="container-fluid">
<ul class="nav navbar-nav">
<li>
<a routerLink="create">
Add Share
</a>
</li>
<li>
<a routerLink="index">
Display Shares
</a>
</li>
</ul>
</div>
</nav>
<div class="container">
<router-outlet></router-outlet>
</div>
Step 10: Make a form in the create a component file.
First, our create.component.ts file looks like this.
// create.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-create',
templateUrl: './create.component.html',
styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {
title = 'Share Market';
constructor() { }
ngOnInit() {
}
}
And then, we need to make the create.component.html form design.
<div class="panel panel-primary">
<div class="panel-body">
<form>
<div class="form-group">
<label class="col-md-4">Share Name</label>
<input type="text" class="form-control" name="name"/>
</div>
<div class="form-group">
<label class="col-md-4">Share Price</label>
<input type="text" class="form-control" name="coin_price"/>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Add</button>
</div>
</form>
</div>
</div>
Now, head over to this. http://localhost:4200/create . It looks like this.
Angular 5 Firebase Tutorial
Step 11: Create services to send http requests.
Type the following command in your terminal.
ng g service share
Now, import the service file into the app.module.ts file.
import { ShareService } from './coin.service';
providers: [ShareService]
Now, first, we will insert the values in the Firebase database.Include the ReactiveFormsModule in the app.module.ts file.
// app.module.ts
import { ReactiveFormsModule } from '@angular/forms';
imports: [
BrowserModule,
AngularFireModule.initializeApp(environment.firebase),
RouterModule.forRoot(appRoutes),
ReactiveFormsModule
],
Then, we are validating the forms. So first write the form HTML in the create.component.html.
<div class="panel panel-primary">
<div class="panel-body">
<form [formGroup]="angForm" novalidate>
<div class="form-group">
<label class="col-md-4">Share Name</label>
<input type="text" class="form-control" formControlName="name" #name />
</div>
<div *ngIf="angForm.controls['name'].invalid && (angForm.controls['name'].dirty || angForm.controls['name'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['name'].errors.required">
Name is required.
</div>
</div>
<div class="form-group">
<label class="col-md-4">Share Price</label>
<input type="text" class="form-control" formControlName="price" #price/>
</div>
<div *ngIf="angForm.controls['price'].invalid && (angForm.controls['price'].dirty || angForm.controls['price'].touched)" class="alert alert-danger">
<div *ngIf="angForm.controls['price'].errors.required">
Price is required.
</div>
</div>
<div class="form-group">
<button (click)="addShare(name.value, price.value)" [disabled]="angForm.pristine || angForm.invalid" class="btn btn-primary">Add</button>
</div>
</form>
</div>
</div>
Also, we need to write the logic of validation in the create.component.ts file.
// create.component.ts
import { Component, OnInit } from '@angular/core';
import { ShareService } from '../../share.service';
import { FormGroup, FormBuilder, Validators } from '@angular/forms';
@Component({
selector: 'app-create',
templateUrl: './create.component.html',
styleUrls: ['./create.component.css']
})
export class CreateComponent implements OnInit {
angForm: FormGroup;
constructor(private shareservice: ShareService, private fb: FormBuilder) {
this.createForm();
}
createForm() {
this.angForm = this.fb.group({
name: ['', Validators.required ],
price: ['', Validators.required ]
});
}
addShare(name, price) {
const dataObj = {
name: name,
price: price
};
this.shareservice.addShare(dataObj);
}
ngOnInit() {
}
}
Write the share.service.ts file to insert the data into the database.
// share.service.ts
import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
@Injectable()
export class ShareService {
private basePath = '/shares';
public items: any;
public item: any;
constructor(private db: AngularFireDatabase) { }
addShare(data) {
const obj = this.db.database.ref(this.basePath);
obj.push(data);
console.log('Success');
}
}
If all of your database configurations are right then now you can insert the values in the Firebase. You can see on your console. If you do not know how to configure the Firebase then check out my React Firebase Tutorial
Step 12: Display the shares data in our application.
Now, go to the index.component.ts file and replace the whole file with the following code.
// index.component.ts
import { Component, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { ShareService } from '../../share.service';
@Component({
selector: 'app-index',
templateUrl: './index.component.html',
styleUrls: ['./index.component.css']
})
export class IndexComponent implements OnInit {
public shares: Observable<any[]>;
constructor(private shareservice: ShareService) { }
ngOnInit() {
this.shares = this.getShares('/shares');
}
getShares(path) {
return this.shareservice.getShares(path);
}
}
Our final share.service.ts file looks like this. I have coded the fetching the data from the firebase function.
// share.service.ts
import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class ShareService {
private basePath = '/shares';
constructor(private db: AngularFireDatabase) { }
addShare(data) {
const obj = this.db.database.ref(this.basePath);
obj.push(data);
console.log('Success');
}
getShares(path): Observable<any[]> {
return this.db.list(path).valueChanges();
}
}
And finally, our view file index.component.html looks like this.
<table class="table table-striped">
<tr>
<th>Share Name</th>
<th>Share Price</th>
</tr>
<tr *ngFor="let share of shares | async">
<td>{{ share.name }}</td>
<td>{{ share.price }}</td>
</tr>
</table>
Firebase Angular Tutorial Example From Scratch
Fork Me On Github
That is it, Guys. Angular Firebase Tutorial With Example From Scratch is over. Thanks.
.
The post Angular Firebase Tutorial With Example From Scratch appeared first on AppDividend.
]]>
https://appdividend.com/2018/01/26/angular-firebase-tutorial-example-scratch/feed/ 10 | __label__pos | 0.980115 |
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.
I try to achieve something like the Facebook does when you type @<NAME_OF_A_FRIEND> in a reply. After you choose a friend, the name of that friend is highlighted with a blueish background, so you know it's a separate entity in that text.
I've "inspect element"-ed that textarea and there is no div placed on top of the textarea.
Can anyone give me a clue about how that is done ?
enter image description here
share|improve this question
5
Facebook make the textarea transparent and put a div below. Try to inspect textarea element with Chrome and remove it, and try to find again the element. – David Rodrigues Dec 8 '11 at 22:13
5 Answers 5
up vote 17 down vote accepted
See this example here. I used only CSS and HTML... The JS is very more complex for now. I don't know exactly what you expect.
HTML:
<div id="textback">
<div id="backmodel"></div>
</div>
<textarea id="textarea">Hey Nicolae, it is just a test!</textarea>
CSS:
#textarea {
background: transparent;
border: 1px #ddd solid;
position: absolute;
top: 5px;
left: 5px;
width: 400px;
height: 120px;
font: 9pt Consolas;
}
#backmodel {
position: absolute;
top: 7px;
left: 32px;
background-color: #D8DFEA;
width: 53px;
height: 9pt;
}
share|improve this answer
3
+1 for working example! – Mike Christensen Dec 8 '11 at 22:28
Thank you very much for your answer AND example. – Nicolae Surdu Dec 9 '11 at 11:19
I have a completely different approach to this issue using HTML5. I use a div with contentEditable="true" instead of a textarea (wich I was using until I got stuck with the same problem you had).
Then if I want to change the background color of a specified part I just wrapp that text with a span.
I am not 100% sure if it is the correct approach as I am a newbie in HTML5 but it works fine in all the browsers I have tested it (Firefox 15.0.1 , Chrome 22.0.1229.79 and IE8).
Hope it helps
share|improve this answer
Makes sense. But I (and apparently Facebook :P) prefer the more generic one :) Thank you nevertheless ;) – Nicolae Surdu Sep 28 '12 at 6:28
You are wellcome Nicolae :-) – José L. Sep 29 '12 at 13:15
But the div doesn't increase in height automatically as you are typing in it . So as you go in typing text , doesn't it start to flow automatically. And then would need js to somehow increase the size of that... – Roshan Khandelwal Jan 12 '14 at 19:14
The textarea has background-color: transparent; the extra div you're looking for is behind it, with the same text and font as the textarea, but different colours.
A short example to illustrate the point:
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<style>
* { font-family: sans-serif; font-size: 10pt; font-weight: normal; }
.wrapper { position: relative; width: 400px; height: 400px; outline: solid 1px #666; }
.wrapper > * { position: absolute; top: 0; left: 0; height: 100%; width: 100%; margin: 0; padding: 0; }
.highlighter { background-color: #fff; color: #fff; }
.highlight { background-color: #9ff; color: #9ff; }
textarea { background-color: transparent; border: 0; }
</style>
</head>
<body>
<div class="wrapper">
<div class="highlighter">
This <span class="highlight">is a</span> demonstration.
</div>
<textarea>
This is a demonstration.
</textarea>
</div>
</body>
</html>
Of course, this does not update the special div as you type into the textarea, you need a lot of JavaScript for that.
share|improve this answer
+1 and thank you very much for your answer but I went with the David's answer because it's more straight forward to me. – Nicolae Surdu Dec 9 '11 at 11:20
hi you can check this jquery autosuggest plugin similar to facebook .I have used this to achive the same functionality you required http://www.devthought.com/2008/01/12/textboxlist-meets-autocompletion/
share|improve this answer
Thank you! Looks awesome. Actually, I'm looking for something like this for iPhone, but rather more complicated. – Nicolae Surdu Feb 20 '12 at 13:40
I would suggest changing the text you want to assign a background inline to to display: inline-block; background-color: #YOURCOLOR;. This should do exactly what you want it to do without all the complexities of some of the above answers.
Ultimately your CSS should look something like this:
.name {display: inline-block; background-color: purple;}
Then add some sort of event listener in jQuery (not sure how you're identifying that it is a name) and inside that conditional put:
$(yourNameSelectorGoesHere).addClass(".name");
share|improve this answer
1
You didn't answer my question (or so I believe): how can I change the style to a part of the text inside a textarea? – Nicolae Surdu Dec 9 '11 at 11:16
The current answer provided does not work. It is not flexible at all. You have to use javascript to listen. I cannot give you an example of an event listener because I do not know enough about what exactly you are looking for. But what I'm doing in my code example is adding a class to a name and giving it a background color. You can only do this if are listening for a name. Once a name is identified simply add a class to it's DOM element that does what you want it to do. Absolutely positioning a div behind it is not workable a solution. – Jesse Atkinson Dec 12 '11 at 19:03
1
I know how to use jQuery. You can't just put elements inside a textarea, only text. – Nicolae Surdu Dec 13 '11 at 7:33
Believe it or not, absolutely positioning a div behind the textarea is exactly what Facebook does. @Nicolae is right - you cannot put elements inside a textarea, so this is one of the only ways to do it. – nathan.f77 Mar 24 '12 at 3:23
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question. | __label__pos | 0.664868 |
HTML5のCanvasでつくるダイナミックな表現―CreateJSを使う
第7回 粒子同士が引き合う力を直線の濃淡で示す
この記事を読むのに必要な時間:およそ 9.5 分
前回は,ランダムに動く粒子それぞれの間にバネのような力を与えてアニメーションさせた。すると,粒子は互いに集まっては離れることを繰り返す,という面白い動きになった(再掲第6回図3)。ここまでのコードは,以下のjsdo.itに掲げてある第6回コード2)。
第6回 図3 オブジェクトがひと固まりに集まっては離れる(再掲)
第6回 図3 オブジェクトがひと固まりに集まっては離れる
第6回 図3 オブジェクトがひと固まりに集まっては離れる
オブジェクトが引合う力の範囲をかぎる
互いに離れれば離れるほど,引き戻す力は強まるというのがバネの性質だ。ただし,それを単純に当てはめたために,仲間から外れた粒子の激しい動きが止められず,しかも仲間はずれは次第に増えてしまうというのが前回の問題だった。
もともと,バネはいくらでも伸び縮みするものではない。むしろ,その動きを正しく保てる範囲はかぎられる。そこで,この粒子のアニメーションでも,互いの間に引合う力が及ぶ距離を決めてしまおう。2点の座標からその間の距離を導くには,三平方の定理を用いる図1)。2点の水平・垂直の各座標の差をそれぞれ2乗し,足し合わせてから平方根を求めればよい。
図1 2点の座標から三平方の定理で距離を求める
</span>図1 2点の座標から三平方の定理で距離を求める </span>図1 2点の座標から三平方の定理で距離を求める
そこで,以下のように力の働く最大距離を変数(limit)で定める。そして,オブジェクト間にバネの力を加える関数(spring())の中で,その距離より近いオブジェクト同士だけ引合うようにする。
水平・垂直それぞれの座標の差(distanceXとdistanceY)は,もともと求めていた。だから,それぞれを2乗して(squareXとsquareY)加え,平方根を計算すれば,距離(distance)が導ける。平方根はMath.sqrt()メソッドで求まる。なお,累乗にはMath.pow()メソッドが使える。だが,Mathクラスの演算は遅くなりがちだ。2乗くらいなら,同じ値を2度掛けたほうが速い。
function spring(object0, object1) {
var distanceX = object1.x - object0.x;
var distanceY = object1.y - object0.y;
var squareX = distanceX * distanceX;
var squareY = distanceY * distanceY;
var distance = Math.sqrt(squareX + squareY);
if (distance < limit) {
var accelX = distanceX * ratio;
var accelY = distanceY * ratio;
object0.velocityX += accelX;
object0.velocityY += accelY;
object1.velocityX -= accelX;
object1.velocityY -= accelY;
}
}
さて,処理の速さを考えるなら,もう一歩踏み込みたい。オブジェクト間の距離を条件に,互いに引合うかどうかを決めた。けれども,距離(distance)の値そのものは計算に使っていない。単に,if条件であらかじめ定めた制限値(limit)と比べただけだ。そうであれば,平方根など求めることはない。比べる制限値の方を2乗しておく。これで,またひとつ計算が減り,Mathクラスのメソッドも使わずに済んだ。
// var limit = 100;
var limit = 100 * 100;
function spring(object0, object1) {
var distanceX = object1.x - object0.x;
var distanceY = object1.y - object0.y;
var squareX = distanceX * distanceX;
var squareY = distanceY * distanceY;
// var distance = Math.sqrt(squareX + squareY);
// if (distance < limit) {
if (squareX + squareY < limit) {
var accelX = distanceX * ratio;
var accelY = distanceY * ratio;
object0.velocityX += accelX;
object0.velocityY += accelY;
object1.velocityX -= accelX;
object1.velocityY -= accelY;
}
}
書き直したJavaScript全体は,以下のコード1のとおりだ。仲間から大きく外れると力が加えられなくなり,近づけば引き戻される。激しくやんちゃな動きをする粒子はめっきり減るはずだ図2)。
図2 オブジェクトの集まりから激しく飛び出す粒子は減る
</span>図2 オブジェクトの集まりから激しく飛び出す粒子は減る
コード1 オブジェクト同士が引合う力の及ぶ範囲をかぎった
var stage;
var stageWidth;
var stageHeight;
var balls = [];
var ballCount = 25;
var ratio = 1 / 2000;
var limit = 100 * 100;
function initialize() {
var canvasElement = document.getElementById("myCanvas");
stage = new createjs.Stage(canvasElement);
stageWidth = canvasElement.width;
stageHeight = canvasElement.height;
for (var i = 0; i < ballCount; i++) {
var nX = Math.random() * stageWidth;
var nY = Math.random() * stageHeight;
var velocityX = (Math.random() - 0.5) * 5;
var velocityY = (Math.random() - 0.5) * 5;
var ball = createBall(3, "black", nX, nY, velocityX, velocityY);
balls.push(ball);
stage.addChild(ball);
}
createjs.Ticker.addEventListener("tick", move);
}
function createBall(radius, color, nX, nY, velocityX, velocityY) {
var ball = new createjs.Shape();
drawBall(ball.graphics, radius, color);
ball.x = nX;
ball.y = nY;
ball.velocityX = velocityX;
ball.velocityY = velocityY;
return ball;
}
function drawBall(myGraphics, radius, color) {
myGraphics.beginFill(color);
myGraphics.drawCircle(0, 0, radius);
}
function move(eventObject) {
for (var i = 0; i < ballCount; i++) {
var ball = balls[i];
var nX = ball.x;
var nY = ball.y;
nX += ball.velocityX;
nY += ball.velocityY;
ball.x = roll(nX, stageWidth);
ball.y = roll(nY, stageHeight);
}
for (i = 0; i < ballCount - 1; i++) {
var ball0 = balls[i];
for (var j = i + 1; j < ballCount; j++) {
var ball1 = balls[j];
spring(ball0, ball1);
}
}
stage.update();
}
function roll(value, length) {
if (value > length) {
value -= length;
} else if (value < 0) {
value += length;
}
return value;
}
function spring(object0, object1) {
var distanceX = object1.x - object0.x;
var distanceY = object1.y - object0.y;
var squareX = distanceX * distanceX;
var squareY = distanceY * distanceY;
if (squareX + squareY < limit) {
var accelX = distanceX * ratio;
var accelY = distanceY * ratio;
object0.velocityX += accelX;
object0.velocityY += accelY;
object1.velocityX -= accelX;
object1.velocityY -= accelY;
}
}
著者プロフィール
野中文雄(のなかふみお)
ソフトウェアトレーナー,テクニカルライター,オーサリングエンジニア。上智大学法学部卒,慶応義塾大学大学院経営管理研究科修士課程修了(MBA)。独立系パソコン販売会社で,総務・人事,企画,外資系企業担当営業などに携わる。その後,マルチメディアコンテンツ制作会社に転職。ソフトウェアトレーニング,コンテンツ制作などの業務を担当する。2001年11月に独立。Web制作者に向けた情報発信プロジェクトF-siteにも参加する。株式会社ロクナナ取締役(非常勤)。
URLhttp://www.FumioNonaka.com/
著書
コメント
コメントの記入 | __label__pos | 0.831355 |
Sum of two numbers is 32. If one of them is -36, then the other number is
This question was previously asked in
CTET Nov 2012 Paper - 2 Maths & Science (L - I/II: Hindi/English/Sanskrit)
View all CTET Papers >
1. -4
2. 4
3. -68
4. 68
Answer (Detailed Solution Below)
Option 4 : 68
Detailed Solution
Download Solution PDF
Given:
Sum of two numbers = 32
One of the two numbers = -36
Calculations:
Let the other number be N
⇒ N + (-36) = 32
⇒ N - 36 = 32
⇒ N = 32 + 36
⇒ N = 68
∴ The other number is 68 | __label__pos | 0.921208 |
You are viewing documentation for Kubernetes version: v1.22
Kubernetes v1.22 documentation is no longer actively maintained. The version you are currently viewing is a static snapshot. For up-to-date documentation, see the latest version.
Configure Multiple Schedulers
Kubernetes ships with a default scheduler that is described here. If the default scheduler does not suit your needs you can implement your own scheduler. Moreover, you can even run multiple schedulers simultaneously alongside the default scheduler and instruct Kubernetes what scheduler to use for each of your pods. Let's learn how to run multiple schedulers in Kubernetes with an example.
A detailed description of how to implement a scheduler is outside the scope of this document. Please refer to the kube-scheduler implementation in pkg/scheduler in the Kubernetes source directory for a canonical example.
Before you begin
You need to have a Kubernetes cluster, and the kubectl command-line tool must be configured to communicate with your cluster. It is recommended to run this tutorial on a cluster with at least two nodes that are not acting as control plane hosts. If you do not already have a cluster, you can create one by using minikube or you can use one of these Kubernetes playgrounds:
To check the version, enter kubectl version.
Package the scheduler
Package your scheduler binary into a container image. For the purposes of this example, you can use the default scheduler (kube-scheduler) as your second scheduler. Clone the Kubernetes source code from GitHub and build the source.
git clone https://github.com/kubernetes/kubernetes.git
cd kubernetes
make
Create a container image containing the kube-scheduler binary. Here is the Dockerfile to build the image:
FROM busybox
ADD ./_output/local/bin/linux/amd64/kube-scheduler /usr/local/bin/kube-scheduler
Save the file as Dockerfile, build the image and push it to a registry. This example pushes the image to Google Container Registry (GCR). For more details, please read the GCR documentation.
docker build -t gcr.io/my-gcp-project/my-kube-scheduler:1.0 .
gcloud docker -- push gcr.io/my-gcp-project/my-kube-scheduler:1.0
Define a Kubernetes Deployment for the scheduler
Now that you have your scheduler in a container image, create a pod configuration for it and run it in your Kubernetes cluster. But instead of creating a pod directly in the cluster, you can use a Deployment for this example. A Deployment manages a Replica Set which in turn manages the pods, thereby making the scheduler resilient to failures. Here is the deployment config. Save it as my-scheduler.yaml:
apiVersion: v1
kind: ServiceAccount
metadata:
name: my-scheduler
namespace: kube-system
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: my-scheduler-as-kube-scheduler
subjects:
- kind: ServiceAccount
name: my-scheduler
namespace: kube-system
roleRef:
kind: ClusterRole
name: system:kube-scheduler
apiGroup: rbac.authorization.k8s.io
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: my-scheduler-as-volume-scheduler
subjects:
- kind: ServiceAccount
name: my-scheduler
namespace: kube-system
roleRef:
kind: ClusterRole
name: system:volume-scheduler
apiGroup: rbac.authorization.k8s.io
---
apiVersion: v1
kind: ConfigMap
metadata:
name: my-scheduler-config
namespace: kube-system
data:
my-scheduler-config.yaml: |
apiVersion: kubescheduler.config.k8s.io/v1beta2
kind: KubeSchedulerConfiguration
profiles:
- schedulerName: my-scheduler
leaderElection:
leaderElect: false
---
apiVersion: apps/v1
kind: Deployment
metadata:
labels:
component: scheduler
tier: control-plane
name: my-scheduler
namespace: kube-system
spec:
selector:
matchLabels:
component: scheduler
tier: control-plane
replicas: 1
template:
metadata:
labels:
component: scheduler
tier: control-plane
version: second
spec:
serviceAccountName: my-scheduler
containers:
- command:
- /usr/local/bin/kube-scheduler
- --config=/etc/kubernetes/my-scheduler/my-scheduler-config.yaml
image: gcr.io/my-gcp-project/my-kube-scheduler:1.0
livenessProbe:
httpGet:
path: /healthz
port: 10251
initialDelaySeconds: 15
name: kube-second-scheduler
readinessProbe:
httpGet:
path: /healthz
port: 10251
resources:
requests:
cpu: '0.1'
securityContext:
privileged: false
volumeMounts:
- name: config-volume
mountPath: /etc/kubernetes/my-scheduler
hostNetwork: false
hostPID: false
volumes:
- name: config-volume
configMap:
name: my-scheduler-config
In the above manifest, you use a KubeSchedulerConfiguration to customize the behavior of your scheduler implementation. This configuration has been passed to the kube-scheduler during initialization with the --config option. The my-scheduler-config ConfigMap stores the configuration file. The Pod of themy-scheduler Deployment mounts the my-scheduler-config ConfigMap as a volume.
In the aforementioned Scheduler Configuration, your scheduler implementation is represented via a KubeSchedulerProfile.
Also, note that you create a dedicated service account my-scheduler and bind the ClusterRole system:kube-scheduler to it so that it can acquire the same privileges as kube-scheduler.
Please see the kube-scheduler documentation for detailed description of other command line arguments and Scheduler Configuration reference for detailed description of other customizable kube-scheduler configurations.
Run the second scheduler in the cluster
In order to run your scheduler in a Kubernetes cluster, create the deployment specified in the config above in a Kubernetes cluster:
kubectl create -f my-scheduler.yaml
Verify that the scheduler pod is running:
kubectl get pods --namespace=kube-system
NAME READY STATUS RESTARTS AGE
....
my-scheduler-lnf4s-4744f 1/1 Running 0 2m
...
You should see a "Running" my-scheduler pod, in addition to the default kube-scheduler pod in this list.
Enable leader election
To run multiple-scheduler with leader election enabled, you must do the following:
Update the following fields for the KubeSchedulerConfiguration in the my-scheduler-config ConfigMap in your YAML file:
• leaderElection.leaderElect to true
• leaderElection.resourceNamespace to <lock-object-namespace>
• leaderElection.resourceName to <lock-object-name>
If RBAC is enabled on your cluster, you must update the system:kube-scheduler cluster role. Add your scheduler name to the resourceNames of the rule applied for endpoints and leases resources, as in the following example:
kubectl edit clusterrole system:kube-scheduler
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
annotations:
rbac.authorization.kubernetes.io/autoupdate: "true"
labels:
kubernetes.io/bootstrapping: rbac-defaults
name: system:kube-scheduler
rules:
- apiGroups:
- coordination.k8s.io
resources:
- leases
verbs:
- create
- apiGroups:
- coordination.k8s.io
resourceNames:
- kube-scheduler
- my-scheduler
resources:
- leases
verbs:
- get
- update
- apiGroups:
- ""
resourceNames:
- kube-scheduler
- my-scheduler
resources:
- endpoints
verbs:
- delete
- get
- patch
- update
Specify schedulers for pods
Now that your second scheduler is running, create some pods, and direct them to be scheduled by either the default scheduler or the one you deployed. In order to schedule a given pod using a specific scheduler, specify the name of the scheduler in that pod spec. Let's look at three examples.
• Pod spec without any scheduler name
apiVersion: v1
kind: Pod
metadata:
name: no-annotation
labels:
name: multischeduler-example
spec:
containers:
- name: pod-with-no-annotation-container
image: k8s.gcr.io/pause:2.0
When no scheduler name is supplied, the pod is automatically scheduled using the default-scheduler.
Save this file as pod1.yaml and submit it to the Kubernetes cluster.
kubectl create -f pod1.yaml
• Pod spec with default-scheduler
apiVersion: v1
kind: Pod
metadata:
name: annotation-default-scheduler
labels:
name: multischeduler-example
spec:
schedulerName: default-scheduler
containers:
- name: pod-with-default-annotation-container
image: k8s.gcr.io/pause:2.0
A scheduler is specified by supplying the scheduler name as a value to spec.schedulerName. In this case, we supply the name of the default scheduler which is default-scheduler.
Save this file as pod2.yaml and submit it to the Kubernetes cluster.
kubectl create -f pod2.yaml
• Pod spec with my-scheduler
apiVersion: v1
kind: Pod
metadata:
name: annotation-second-scheduler
labels:
name: multischeduler-example
spec:
schedulerName: my-scheduler
containers:
- name: pod-with-second-annotation-container
image: k8s.gcr.io/pause:2.0
In this case, we specify that this pod should be scheduled using the scheduler that we deployed - my-scheduler. Note that the value of spec.schedulerName should match the name supplied for the scheduler in the schedulerName field of the mapping KubeSchedulerProfile.
Save this file as pod3.yaml and submit it to the Kubernetes cluster.
kubectl create -f pod3.yaml
Verify that all three pods are running.
kubectl get pods
Verifying that the pods were scheduled using the desired schedulers
In order to make it easier to work through these examples, we did not verify that the pods were actually scheduled using the desired schedulers. We can verify that by changing the order of pod and deployment config submissions above. If we submit all the pod configs to a Kubernetes cluster before submitting the scheduler deployment config, we see that the pod annotation-second-scheduler remains in "Pending" state forever while the other two pods get scheduled. Once we submit the scheduler deployment config and our new scheduler starts running, the annotation-second-scheduler pod gets scheduled as well.
Alternatively, you can look at the "Scheduled" entries in the event logs to verify that the pods were scheduled by the desired schedulers.
kubectl get events
You can also use a custom scheduler configuration or a custom container image for the cluster's main scheduler by modifying its static pod manifest on the relevant control plane nodes.
Last modified November 02, 2021 at 7:56 PM PST : Update config refs to KubeSchedulerConfiguration (7449bb36a0) | __label__pos | 0.970155 |
URL Keeper with HTML, CSS, and JavaScript (Source Code)
Faraz
By Faraz -
Learn to create URL Keeper with HTML, CSS, and JavaScript in this step-by-step tutorial. Manage and save your URLs with ease!
URL Keeper with HTML, CSS, and JavaScript.jpg
Table of Contents
1. Project Introduction
2. HTML Code
3. CSS Code
4. JavaScript Code
5. Preview
6. Conclusion
URL Keeper is a powerful web application that simplifies the process of managing and saving website URLs. In this tutorial, we will guide you through the process of building your own URL Keeper using HTML, CSS, and JavaScript. With this user-friendly tool, you can save and organize your favorite URLs effortlessly.
Join My Telegram Channel to Download the Project Source Code: Click Here
Prerequisites:
Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.
Source Code
Step 1 (HTML Code):
To get started, create a basic HTML structure for URL Keeper. This structure will serve as the foundation for your web application.
Let me explain each part of the code:
1. <!DOCTYPE html>: This is the document type declaration, which specifies that the document is an HTML5 document.
2. <html lang="en">: This is the opening <html> tag that defines the root element of the HTML document. The lang attribute is set to "en" to indicate that the language of the document is English.
3. <head>: This is the <head> section of the HTML document. It contains metadata and information about the page, but it's not displayed on the web page itself.
• <meta charset="UTF-8">: This meta tag sets the character encoding of the document to UTF-8, which is a character encoding that supports a wide range of characters and languages.
• <meta http-equiv="X-UA-Compatible" content="IE=edge">: This meta tag is typically used for Internet Explorer compatibility and suggests that the page should be displayed in the highest available mode in Internet Explorer.
• <meta name="viewport" content="width=device-width, initial-scale=1.0">: This meta tag is often used for responsive web design. It tells the browser to set the initial zoom level to 1.0 and adjust the page's width to match the device's width.
• <link rel="stylesheet" href="styles.css">: This line links an external stylesheet named "styles.css" to the HTML document. Stylesheets are used for defining the visual appearance of the web page.
• <title>URL Keeper</title>: This sets the title of the web page, which is displayed in the browser's title bar or tab. In this case, the title is "URL Keeper."
4. <body>: This is the opening <body> tag, which contains the visible content of the web page.
• <h1>URL KEEPER</h1>: This is a top-level heading (h1) that displays the text "URL KEEPER."
• <p>Keep your favorite urls in one place 🔗</p>: This is a paragraph (p) element that displays the text "Keep your favorite URLs in one place" and includes a Unicode emoji (🔗) represented by the character entity reference "."
• <input type="text" id='input-el'>: This is an input element of type "text" where users can input text. It has an "id" attribute set to "input-el" for identification in scripts or styles.
• <button id='inpbtn-el'>SAVE LINK</button>: This is a button element with the id "inpbtn-el," which displays the text "SAVE LINK." It can be used for saving a link.
• <button id='tabbtn-el'>SAVE TAB</button>: Similar to the previous button, this button with the id "tabbtn-el" displays the text "SAVE TAB" and can be used for saving a tab or link.
• <button id='clbtn-el'>CLEAR ALL</button>: This button, identified by the id "clbtn-el," displays the text "CLEAR ALL" and can be used to clear all saved links or tabs.
• <ul id="ul-el">: This is an unordered list (ul) element with the id "ul-el." The list items (li) inside it will be added dynamically using JavaScript to display saved URLs.
• <script src="script.js"></script>: This script tag links an external JavaScript file named "script.js" to the HTML document. JavaScript is used for adding interactivity and functionality to the web page.
Step 2 (CSS Code):
A visually appealing user interface is essential for a user-friendly experience. Use CSS to style URL Keeper. Create a CSS file and link it to your HTML document.
Let me explain each part:
1. body:
• Sets the left and right margins to 0, effectively removing any default margin.
• Adds 10 pixels of padding on all sides of the body element.
• Specifies the font family to be used, with fallback options if Arial is not available.
• Ensures a minimum width of 400 pixels.
• Sets the background color to black.
2. h1:
• Removes the default margin at the bottom of <h1> elements.
• Sets the text color to #3463c9 (a shade of blue).
3. p:
• Removes the default margin at the top of <p> elements.
• Sets the text color to #e67518 (a shade of orange).
4. input:
• Makes all <input> elements extend to 100% of their container width.
• Adds a 1-pixel solid border with the color #4af029.
• Sets the padding inside the input element to 10 pixels.
• The box-sizing property ensures that the padding and border are included in the total width.
• Adds a margin at the bottom of 4 pixels to separate input elements.
5. button:
• Sets the background color to #e944e1 (a shade of pink/purple).
• Adds a slight border radius (rounded corners) of 1 pixel.
• Sets the text color to white.
• Adds padding of 10 pixels on the top and bottom and 20 pixels on the left and right.
• Adds a 1-pixel solid border with the color #5f9341.
• Makes the text bold.
6. #clbtn-el:
• This targets an element with the id of "clbtn-el."
• Sets the background to white (rgb(255, 255, 255)).
• Changes the text color to #5f9341 (a shade of green).
7. ul:
• Adds a margin of 20 pixels at the top of unordered lists.
• Removes the default list-style (bullets).
• Sets the padding on the left of the list to 0.
8. li:
• Adds a margin of 5 pixels at the top of list items.
9. a:
• Sets the text color of links to white.
• Defines a font size of 1 rem (relative to the root font size).
body{
margin: 0;
padding: 10px;
font-family: Arial, Helvetica, sans-serif;
min-width: 400px;
background-color: black;
}
h1{
margin-bottom: 0;
color: #3463c9;
}
p{
margin-top: 0;
color: #e67518;
}
input{
width: 100%;
border: 1px solid #4af029;
padding: 10px;
box-sizing: border-box;
margin-bottom: 4px;
}
button{
background: #e944e1;
border-radius: 1px;
color: white;
padding: 10px 20px;
border: 1px solid #5f9341;
font-weight: bold;
}
#clbtn-el{
background: rgb(255, 255, 255);
color: #5f9341;
}
ul {
margin-top: 20px;
list-style: none;
padding-left: 0;
}
li {
margin-top: 5px;
}
a {
color: #ffffff;
font-size: 1rem;
}
Step 3 (JavaScript Code):
Now, let's add JavaScript to make URL Keeper functional. Start by linking your JavaScript file:
Let's break down what the code is doing step by step:
1. It begins by defining several constants and variables:
• inputEl, inpBtnEl, tabBtnEl, and clBtnEl are constants that store references to HTML elements with specific IDs using document.querySelector(). These elements are form inputs and buttons on your web page.
• ulEl is a variable that stores a reference to an HTML element with an ID, which is an unordered list where URLs will be displayed.
• urlsFromLocalStorage attempts to retrieve and parse JSON data from the 'urls' key in the browser's local storage. If data is found, it populates the urls variable with this data, assuming it's an array.
• An empty array urls is declared, which will be used to store the list of URLs.
2. The code then checks if there are URLs stored in local storage:
• If there are URLs (urlsFromLocalStorage is not null), it populates the urls array with the stored data and calls the renderUrls() function to display them in the HTML.
3. Event listeners are set up for three different buttons:
• inpBtnEl (presumably a button for user input): When clicked, it checks if the inputEl (presumably an input field) has a value. If it does, it pushes the value (a URL) into the urls array, clears the input field, stores the updated urls array in local storage, and updates the display by calling renderUrls(). If the input field is empty, it displays an alert.
• tabBtnEl (a button for capturing the current tab's URL): When clicked, it uses the Chrome Extension API (assuming this is a Chrome extension) to query for the active tab in the current window. It then pushes the URL of the active tab into the urls array, stores the updated urls array in local storage, and updates the display using renderUrls().
• clBtnEl (presumably a button to clear stored data): When clicked, it clears the local storage and resets the urls array to an empty state. It then updates the display by calling renderUrls() to remove all displayed URLs.
4. The renderUrls(urls) function is defined to render the list of URLs in the HTML page. It generates a list of <li> elements, each containing an anchor <a> tag with the URL as the href and text. The resulting HTML string is inserted into the ulEl element, updating the displayed list of URLs on the page.
const inputEl = document.querySelector('#input-el')
const inpBtnEl = document.querySelector('#inpbtn-el')
const tabBtnEl = document.querySelector('#tabbtn-el')
const clBtnEl = document.querySelector('#clbtn-el')
let ulEl = document.querySelector('#ul-el')
const urlsFromLocalStorage = JSON.parse(localStorage.getItem('urls'))
let urls = []
if(urlsFromLocalStorage){
urls = urlsFromLocalStorage
renderUrls(urls)
}
inpBtnEl.addEventListener('click', function(){
if(inputEl.value){
urls.push(inputEl.value)
inputEl.value = ""
localStorage.setItem('urls', JSON.stringify(urls))
renderUrls(urls)
}
else{
alert('Please enter url.')
}
})
tabBtnEl.addEventListener('click', function(){
chrome.tabs.query({active: true, currentWindow: true}, function(tabs){
urls.push(tabs[0].url)
localStorage.setItem("urls", JSON.stringify(urls))
renderUrls(urls)
})
})
clBtnEl.addEventListener('click', function(){
localStorage.clear()
urls = []
renderUrls(urls)
})
function renderUrls(urls){
let listItems = ""
for(let i = 0; i < urls.length; i++){
listItems += `
<li>
<a href=${urls[i]}>${urls[i]}</a>
</li>
`
}
ulEl.innerHTML = listItems
}
Final Output:
URL Keeper with HTML, CSS, and JavaScript.gif
Conclusion:
Congratulations! You've successfully created your URL Keeper web application. With this tool, you can efficiently save, organize, and manage your bookmarks. Its user-friendly design and robust functionality make it valuable to your web development toolkit.
In conclusion, URL Keeper simplifies managing URLs, making it an invaluable tool for web developers. Start building your URL Keeper today and enjoy efficient URL management.
That’s a wrap!
I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.
Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.
And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!
Thanks!
Faraz 😊
End of the article
Subscribe to my Newsletter
Get the latest posts delivered right to your inbox
Latest Post | __label__pos | 0.974985 |
0
I'm creating a small website that tells a story by using css and sprite animation.
The problem I'm encountering is that I do not know how to change the keyframes once I have set them in the css files expecially while I try to make it compatible with all of the browsers.
Here is what I have,
the main part of the css:
#ManSprite{
overflow:hidden;
width:200px;
height:200px;
position:absolute;
top:280px;
left:140px;
background-image: url("http://imageshack.com/a/img571/1710/2r1h.png");
z-index:99;
animation: play .4s steps(2) infinite;
-webkit-animation: play .4s steps(2) infinite;
-moz-animation: play .4s steps(2) infinite;
-ms-animation: play .4s steps(2) infinite;
-o-animation: play .4s steps(2) infinite;
}
@keyframes play {
from { background-position: -200px; }
to { background-position: -600px; }
}
@-webkit-keyframes play {
from { background-position: -200px; }
to { background-position: -600px; }
}
@-moz-keyframes play {
from { background-position: -200px; }
to { background-position: -600px; }
}
@-ms-keyframes play {
from { background-position: -200px; }
to { background-position: -600px; }
}
@-o-keyframes play {
from { background-position: -200px; }
to { background-position: -600px; }
}
Then in my javascript I would like to change the background position for every keyframe but I'm not sure how to change it. I've tried the following but it does not work.
var StoryPart = 0;
var fromArray = new Array("0px", "-200px", "-800px", "-1400px", "-2200px", "-3200px");
var toArray = new Array("0px", "-600px", "-1400px", "-2200px", "-3230px", "-4000px");
var stepsArray = new Array(0, 2, 3, 4, 5, 4);
function nextBtn() {
StoryPart++;
startChange();
}
// begin the new animation process
function startChange() {
// remove the old animation from our object
document.getElementById('ManSprite').style.webkitAnimationName = "none";
document.getElementById('ManSprite').style.animationName = "none";
document.getElementById('ManSprite').style.msAnimationName = "none";
document.getElementById('ManSprite').style.oAnimationName = "none";
document.getElementById('ManSprite').style.mozAnimationName ="none";
// call the change method, which will update the keyframe animation
setTimeout(function () { change("play", fromArray[StoryPart], toArray[StoryPart]); }, 0);
}
// search the CSSOM for a specific -webkit-keyframe rule
function findKeyframesRule(rule) {
// gather all stylesheets into an array
var ss = document.styleSheets;
// loop through the stylesheets
for (var i = 0; i < ss.length; ++i) {
// loop through all the rules
for (var j = 0; j < ss[i].cssRules.length; ++j) {
// find the -webkit-keyframe rule whose name matches our passed over parameter and return that rule
if (ss[i].cssRules[j].type == window.CSSRule.WEBKIT_KEYFRAMES_RULE && ss[i].cssRules[j].name == rule
|| ss[i].cssRules[j].type == window.CSSRule.KEYFRAMES_RULE && ss[i].cssRules[j].name == rule
)
return ss[i].cssRules[j];
}
}
// rule not found
return null;
}
// remove old keyframes and add new ones
function change(anim, fromValue, toValue) {
// find our -webkit-keyframe rule
var keyframes = findKeyframesRule(anim);
// remove the existing 0% and 100% rules
keyframes.deleteRule("0%");
keyframes.deleteRule("100%");
// create new 0% and 100% rules with random numbers
keyframes.insertRule("0% {background-position: " + fromValue + ";}");
keyframes.insertRule("100% {background-position: " + toValue + ";}");
// assign the animation to our element (which will cause the animation to run)
document.getElementById('ManSprite').style.webkitAnimationName = anim;
document.getElementById('ManSprite').style.animationName = anim;
document.getElementById('ManSprite').style.msAnimationName = anim;
document.getElementById('ManSprite').style.oAnimationName = anim;
document.getElementById('ManSprite').style.mozAnimationName = anim;
}
For some reason in Chrome, it doesn't find any cssRule inside the findKeyframesRule method, but in firefox it does. Firefox crashes, however, on this line
keyframes.insertRule("0% {background-position: " + fromValue + ";}");
which confuses me because it was able to use deleteRule well.
Anyone ever work with these?
• If those values you are trying to set are not dynamic, then I’d rather put them into different stylesheet rules in the first place, and just switch between the applied rules by changing f.e. the class of the element(s) with JS. – CBroe Jan 30 '14 at 12:18
• @CBroe so you mean create multiple plays,play1,play2,etc and just use the different values I have stored? – Kelsey Abreu Jan 30 '14 at 12:37
• following post might have an answer you are looking for: stackoverflow.com/questions/10342494/… – webdev-dan Jan 30 '14 at 15:08
• @webdev-dan already checked that. I'm no longer having the MAIN problem, the problem I am having now is insertRule not working in firefox for some reason. – Kelsey Abreu Jan 30 '14 at 15:15
• never used this ...but as i noticed in docs (developer.mozilla.org/en-US/docs/Web/API/… ) insertRule needs 2 arguments - like this: keyframes.insertRule("0% {background-position: " + fromValue + ";}", keyframes.cssRules.length); – webdev-dan Jan 30 '14 at 15:25
Your Answer
By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy
Browse other questions tagged or ask your own question. | __label__pos | 0.971391 |
Tell me more ×
Facebook - Stack Overflow is a question and answer site for facebook developers. It's 100% free, no registration required.
Facebook and Stack Exchange are now working together to support the Facebook developer community. Facebook engineers participate here along with the best Facebook developers in the world. If you have a technical question about Facebook, this is the best place to ask.
I'm creating a CC3PlaneNode (cocos3d) with code that looks something like this:
CC3PlaneNode *bnode = [CC3PlaneNode nodeWithName: name];
CC3Texture *texture = [CC3Texture textureFromFile: texName];
[bnode populateAsCenteredRectangleWithSize: sz
andTessellation: ccg(1, 1)
withTexture: texture
invertTexture: YES];
bnode.material.specularColor = kCCC4FLightGray;
bnode.material.emissionColor = kCCC4FWhite;
bnode.material.isOpaque = NO;
bnode.shouldCullBackFaces = NO;
bnode.isTouchEnabled = YES;
bnode.location = loc;
[bnode retainVertexLocations];
Under certain circumstances, I'd like the plane to display the mirror image of its texture (a la the Flip Horizontal feature on many image programs.) I don't just want to flip the plane, itself, because that would throw out-of-position all of it's child-nodes, which is undesirable behaviour.
That is, if X & Y are parts of my texture, and "c" and "c'" are child-nodes in this diagram:
+--------+
| |
| x y |
| |
+--------+
c c'
after the flip, I want things to look like this:
+--------+
| |
| y x |
| |
+--------+
c c'
Other than not wanting to rotate/spin/flip the plane, itself, I'm otherwise pretty flexible on a solution.
Any hints?
Thanks!
share|improve this question
Know someone who can answer? Share a link to this question via email, Google+, Twitter, or Facebook.
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Browse other questions tagged or ask your own question. | __label__pos | 0.565027 |
How to use not like operator in PostgreSQL?
by hal.littel , in category: PHP Databases , a year ago
How to use not like operator in PostgreSQL?
Facebook Twitter LinkedIn Telegram Whatsapp
2 answers
Member
by gilbert , a year ago
@hal.littel
In PostgreSQL, you can use the NOT LIKE operator to find rows that do not match a specific pattern.
Here is the basic syntax for using NOT LIKE in a SELECT statement:
1
2
3
SELECT column1, column2, ...
FROM table_name
WHERE column1 NOT LIKE pattern;
For example, suppose you have a table called customers with a name column. To select all rows from the customers table where the name does not contain the string 'John', you can use the following query:
1
SELECT * FROM customers WHERE name NOT LIKE '%John%';
You can also use the NOT LIKE operator with the ESCAPE clause to specify an escape character for the pattern. For example:
1
SELECT * FROM customers WHERE name NOT LIKE '%John%%' ESCAPE '';
This will select all rows where the name column does not contain the string 'John%'. The character is used as the escape character, so it tells PostgreSQL to treat the % character as a literal character and not as a wildcard.
I hope this helps! Let me know if you have any questions.
Member
by darion , 17 days ago
@hal.littel
The LIKE and NOT LIKE operators in PostgreSQL are used to compare a value to a pattern using wildcard characters. The basic syntax for using the NOT LIKE operator in PostgreSQL is:
SELECT column1, column2, ... FROM table_name WHERE column1 NOT LIKE pattern;
The pattern can include the following wildcard characters:
• %: Matches any sequence of characters (including zero characters).
• _: Matches any single character.
For example, if you have a table called employees with a first_name column, and you want to select all rows where the first name does not start with 'J', you can use the following query:
SELECT * FROM employees WHERE first_name NOT LIKE 'J%';
This will select all rows where the first_name column does not start with the letter 'J'. You can also use the % wildcard to match any characters after 'J'.
You can combine the % wildcard with other characters to create more complex patterns. For example, if you want to select all rows where the first name does not contain 'ohn', you can use the following query:
SELECT * FROM employees WHERE first_name NOT LIKE '%ohn%';
This will select all rows where the first_name column does not contain the string 'ohn' anywhere in it.
Remember that the NOT LIKE operator is case-sensitive. If you want to perform a case-insensitive search, you can use the ILIKE operator instead.
I hope this clarifies how to use the NOT LIKE operator in PostgreSQL. Let me know if you have any further questions! | __label__pos | 0.99874 |
How do I transfer data from one PS3 to another?
1. In the system settings menu it mentions there is a way to transfer all data from the current PS3 to a new one. How is this done? Is there a USB cable or some other kind of transfer cable that can connect to another PS3? Are downloadables like Rock Band songs or PSN games able to be transfered? Also, what can't be transferred?
User Info: GameBeaten
GameBeaten - 6 years ago
Accepted Answer
1. ok...first make sure your system software is up to date...then....plug an ethernet cable to the back of both systems...go to system settings....transfer data utility...and set up one system to send out the data...and the other to receive the data...now as far as what can and can't be transferred...i believe all data on your PS3 can be transferred with the exception of trophies which you have to sync to the server....
User Info: GuttaBoyz19
GuttaBoyz19 - 6 years ago 0 0
This question has been successfully answered and closed. | __label__pos | 0.568845 |
Nameless Vigilantes Favorite
Practitioner:
Date:
Apr 17 2003
Location:
Online
Anonymous (used as a mass noun) is a loosely associated hacktivist group. It originated in 2003 on the imageboard 4chan, representing the concept of many online and offline community users simultaneously existing as an anarchic, digitized global brain.
It is also generally considered to be a blanket term for members of certain Internet subcultures, a way to refer to the actions of people in an environment where their actual identities are not known. It strongly opposes Internet censorship and surveillance, and has hacked various government websites. It has also targeted major security corporations.It also opposes Scientology and government corruption. Its members can be distinguished in public by the wearing of stylised Guy Fawkes masks.
In its early form, the concept was adopted by a decentralized online community acting anonymously in a coordinated manner, usually toward a loosely self-agreed goal, and primarily focused on entertainment. Beginning with 2008, the Anonymous collective became increasingly associated with collaborative, international hacktivism. They undertook protests and other actions in retaliation against anti-digital piracy campaigns by motion picture and recording industry trade associations.Actions credited to "Anonymous" were undertaken by unidentified individuals who applied the Anonymous label to themselves as attribution. They have been called the freedom fighters of the Internet,[11] a digital Robin Hood,and "anarchic cyber-guerrillas."
Posted by mim523 on | __label__pos | 0.56892 |
Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.
I keep getting 'warning: control reaches end of non-void function' with this code:
static show_message(GtkMessageType type, const char* text, const char* details)
{
GtkWidget *dialog;
g_assert(text);
dialog = gtk_message_dialog_new(NULL, DIALOG_FLAGS, type, GTK_BUTTONS_CLOSE,
"%s", text);
if (details) {
gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(dialog), "%s", details);
}
gtk_dialog_run(GTK_DIALOG (dialog));
gtk_widget_destroy(dialog);
}
When I compile the above code I get Warning (ie control reaches end of non-void function):
gui.c: warning: return type defaults to 'int'
gui.c: In function 'show_message':
gui.c: warning: control reaches end of non-void function
How can I get rid of this warning?
Thanks.
share|improve this question
1 Answer 1
up vote 6 down vote accepted
You need to specify the return value of the show_message() function as void, otherwise it is assumed int. Like this:
static void show_message(GtkMessageType type, const char* text, const char* details)
{
/* ... */
}
share|improve this answer
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question. | __label__pos | 0.978715 |
xorl %eax, %eax
CVE-2008-5025: hfs_cat_find_brec() Local Buffer Overflow
leave a comment »
This vulnerability is present in 2.6 Linux kernel releases up to 2.6.28-rc1 which is not vulnerable. The provided code will be from Linux kernel 2.6.27.5. The flawed function
was written by Paul H. Hargrove of Ardis Technologies and it is located at fs/hfs/catalog.c line 174. The vulnerable function is:
174 int hfs_cat_find_brec(struct super_block *sb, u32 cnid,
175 struct hfs_find_data *fd)
176 {
177 hfs_cat_rec rec;
178 int res, len, type;
179
And is being used to get a catalog entry for the given ID received by varible cnid. Its first argument is the standard super block structure provided by linux/fs.h and its third
is pointer to an HFS’ structure defined at fs/hfsplus/hfsplus_fs.h which keeps track of a binary tree structure used for more efficient search on the file system. Next, at line 177 is
a declaration of hfs_cat_rec variable, this data type is defined at fs/hfs/hfs.h as a union which is being used to describe a catalog tree record.
180 hfs_cat_build_key(sb, fd->search_key, cnid, NULL);
181 res = hfs_brec_read(fd, &rec, sizeof(rec));
182 if (res)
183 return res;
184
The call to hfs_cat_build_key() provides fd->search_key with the catalog name on success, else it sets it sets it to zero. The following call to hfs_brec_read() uses the given hfs_find_data pointer (first argument) to find the record in the binary tree. If this does not success, it returns a non-zero value, else it checks its length to be less than its third argument, reads it and returns zero. That is, the above snippet locates the requested record
and initializes rec to this entry. Next,
185 type = rec.type;
186 if (type != HFS_CDR_THD && type != HFS_CDR_FTH) {
187 printk(KERN_ERR "hfs: found bad thread record in catalog\n");
188 return -EIO;
189 }
190
Integer type has now the type of the requested record and if it is neither a directory (HFS_CDR_THD) nor a file thread (HFS_CDR_FTH) an error is being printed and the function terminates with error on Input/Ouput operation. Lastly,
191 fd->search_key->cat.ParID = rec.thread.ParID;
192 len = fd->search_key->cat.CName.len = rec.thread.CName.len;
The search key’s binary tree structure parent ID is being replaced with the requsted entry’s one and at line 192 the length field of this new catalog name is also updated with the requested one. Finally,
193 memcpy(fd->search_key->cat.CName.name, rec.thread.CName.name, len);
194 return hfs_brec_find(fd);
195 }
The requested catalog name is copied to the binary tree search structure’s field using memcpy() and a size limit of the source string. At last, it calls hfs_brec_find() to find the requsted record which is now stored on the hfs_find_data structure. This is a classic overflow case since the user controls both the requsted catalog name, its length and the search_key‘s buffer which is only 31 bytes as defined at fs/hfs/hfs.h
#define HFS_NAMELEN 31 /* maximum length of an HFS filename */
Attackers have complete control over the copied data at line 193 using the memcpy library call. This means that a malicious user could construct a filename that when parsed by the HFS will be inserted in the binary tree it could lead to buffer overflow in the kernel space. To do this an attacker could construct a malicious HFS image with tools like mkisofs(8).
Strangely enough, various vulnerability databases identify this vulnerability as a denial of service attack. Memory corruption bugs should never be treated as DoS, since in most cases can lead to code execution one way or another.
Advertisements
Written by xorl
January 1, 2009 at 11:48
Posted in bugs, linux
Leave a Reply
Fill in your details below or click an icon to log in:
WordPress.com Logo
You are commenting using your WordPress.com account. Log Out / Change )
Twitter picture
You are commenting using your Twitter account. Log Out / Change )
Facebook photo
You are commenting using your Facebook account. Log Out / Change )
Google+ photo
You are commenting using your Google+ account. Log Out / Change )
Connecting to %s | __label__pos | 0.792761 |
1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
2. MapleStory Europe has migrated to MapleStory Global! This section is readonly now.
Dismiss Notice
Europe Leveling too fast bans?
Discussion in 'Discussion' started by dolan, Sep 6, 2010.
1. dolan
dolan Active Member
I was botting all night and got to level 30 in less than 24 hours, then I got perm banned lol
So I was thinking... does leveling too fast makes GMs check up on you?
2. Panete
Panete CCPLZ Donor Donor
Level 30 in 1 day isnt fast leveling.
3. NonLeaf
NonLeaf Well-Known Member
Lvl 30 is fast leveling? lol. I did 1-43 and some guys can do 1-60 in 1 day. lol
4. Benn
Benn Well-Known Member
Depends how long you can bot. I can only bot a few hours a day so i would be more than happy if i could get 1-30.
5. dolan
dolan Active Member
1-60 in one day!! how do you do that?
I thought 1-30 was fast cos I was constantly botting 24 hours straight
So you guys think it was just bad luck a GM stumbled across my path?
6. Benn
Benn Well-Known Member
Where were you botting?
7. dolan
dolan Active Member
Dammit, i have a strong dislike for GMs.
I was botting in Dungeon: Southern Forest II in ellina lol, bad place? no? killing slimes
How do you guys level so quickly though?
8. Adamkidd
Adamkidd Well-Known Member
I do Pq's I only use bots for Godmodee :) But try monsters in your level range.
9. dolan
dolan Active Member
If I do that, then it takes about 4 hits to kill them.
Someone once told me, It's optimal to kill monsters in 1 or 2 hits?
10. Onurrr
Onurrr Well-Known Member
i was botting at mini dungeons... but got banned... idk how this is possible
11. Zilejiko
Zilejiko Member
GM's Can go ANYWHEREEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE&#??%/#%&"%!"#!"
12. Tattuffino
Tattuffino Member
lol, my ranger 9x spearman 63 and bandit lv 50 got banned in 2days.. pretty lame
13. imagine
imagine Member
Doesnt suprise me that it took you a day if you stay at the slimes all time.
14. dolan
dolan Active Member
i made another account and moved onto pigs instead as it seems slimes will always get me banned...
improvement i guess, I didn't get banned and got to level 31 now lol
15. markb95
markb95 Banned Banned
Botting with my aran sucks pretty hard, dcing all the time. Didnt happen for me in the beginning, Now i cant bot for 5 minutes without dc. Hope next patch there will be better hacks, i wanna hack my lvl 85 NW to 120.
16. deno
deno Member
11X aran not banned yet... trying to get it to 13X...
17. Hyack
Hyack Well-Known Member
GameMasters are active at specific times each day. Most between 9:00AM-11:00AM.
Watch out on which times you are hacking.
18. pichka2
pichka2 New Member
lvling from 1-30 in 7hrs is fast lvling =) , you just got catched by a GM =) Bad luck
Share This Page | __label__pos | 0.510533 |
Internet
Fact Checked
What is Supranet?
Terry Masters
Terry Masters
The Supranet is the network communication infrastructure that represents the symbiotic relationship between the electronic and the physical worlds. The crux of the Supranet concept is the connectivity of embedded computers, wireless networking, bidirectional interfacing technology, and applications that are adaptive across various devices. Mobile business, or m-business, is considered the primary driving force behind the continued development of the Supranet.
This term was first coined in 2000 by the US-based information technology research and advisory firm Gartner, Inc. as part of its framework analysis on convergent communications. The concept was further developed as part of a series of seminal research papers published by Gartner employees over the course of 2001. Over the years, the term never became quite as ubiquitous as the word “Internet,” but some of the definitions and subsumed terms that fleshed out the concept have become popular, and many of the underlying concepts and predictions have proven prescient.
Man holding computer
Man holding computer
The physical word, or p-world, that is part of the Supranet definition is comprised of the tangible objects such as paper, houses, people, and vehicles that need to be connected to the electronic world, or e-world, of devices, such as phones, computers, cameras, and televisions. Under the Supranet concept, the e-world devices are connected to the p-world through embedded computers with bi-directional interfacing that allows the device to transmit identifying information about the user or uniquely tag the information being transmitted. Wireless networking and smart application architecture that can adapt across devices and allow profile management is what powers the information exchange between worlds.
Gartner theorized that the development of mobile business would drive the development of the Supranet. Mobile technologies, such as Bluetooth, GPS, geotagging, and Wireless Application Protocol, that make communication between the physical and electronic worlds easier and more secure support the mobile Supranet lifestyle. People using the Supranet can be connected anytime and anyplace, and can be located and tracked through the devices they use, ultimately benefiting electronic commerce.
A natural progression of the Supranet is the increasing convergence of the physical and electronic worlds into a virtual world that mirrors the real world with increasing precision. Products, such as gaming systems, that convert three-dimensional movement in the real world to movements in a digital landscape are an example of the Supranet at work. Many of the location-mapping and geo-tagging products offered other Internet companies are also examples of the Supranet concept in practice.
You might also Like
Discuss this Article
Post your comments
Login:
Forgot password?
Register:
• Man holding computer
Man holding computer | __label__pos | 0.950241 |
9. Counting in specific contexts
Section Contexts of widget Count’s interface lets the user define the contexts in which units should be counted. Thus, while the settings of section Units affect the columns of the resulting table, those of section Contexts affect its rows.
In the example of the previous section, setting Mode to No context indicated that units were to be counted globally in the selected segmentation; as a result, the resulting table contained a single row (aside from the header row). Orange Textable offers three other modes corresponding to three different definitions of contexts.
Interface of widget Count, Sliding window mode
Figure 1: Interface of widget Count, Sliding window mode.
When Mode is set to Sliding window (see figure 1 above), context is defined as a “window” of n consecutive segments which “slides” from the beginning to the end of the segmentation. In the case of the letter segmentation of a simple example (as obtained with the schema illustrated in the previous section), setting the number of segments in the window (Window size) to 5 yields the following successive contexts: asimp, simpl, imple, mplee, pleex, and so on (see table 1 below). This mode is useful for studying the evolution of unit frequencies throughout a segmentation.
Table 1: Frequency of letters in a “sliding window” of size 5.
a e i m l p s x
1 1 0 1 1 0 1 1 0
2 0 0 1 1 1 1 1 0
3 0 1 1 1 1 1 0 0
4 0 2 0 1 1 1 0 0
5 0 2 0 0 1 1 0 1
6 1 2 0 0 1 0 0 1
7 1 2 0 1 0 0 0 1
8 1 1 0 1 0 1 0 1
9 1 0 0 1 1 1 0 1
10 1 1 0 1 1 1 0 0
When Mode is set to Left-right neighborhood (see figure 2), context is defined on the basis of adjacent segment types occurring to the left and/or right of each position.
Interface of widget Count, Left-right neighborhood mode
Figure 2: Interface of widget Count, Left-right neighborhood mode.
For instance, setting Left context size to 1 and Right context size to 0 amounts to counting the frequency of each segment type given the type that occurs immediately to its left. This particular table is often called “transition matrix” (see table 2 below). The string selected in the Unit position marker string is used to indicate the position where units appear in the context. Thus, table 2 shows that both m and s appear once immediately to the right of an a (i.e. in context a_). To take another example, setting Right context size to 2, we would find that e occurs once both in context l_ex and e_xa.
Table 2: Frequency of letter (row) to letter (column) transitions.
a e i m l p s x
a_ 0 0 0 1 0 0 1 0
s_ 0 0 1 0 0 0 0 0
i_ 0 0 0 1 0 0 0 0
m_ 0 0 0 0 0 2 0 0
p_ 0 0 0 0 2 0 0 0
l_ 0 2 0 0 0 0 0 0
e_ 0 1 0 0 0 0 0 1
x_ 1 0 0 0 0 0 0 0
Finally, when Mode is set to Containing segmentation, unit types are counted whithin the segment types of a second segmentation, as illustrated in table 2 here (frequency of letters whithin words). Segment A is considered to be contained within segment B if the following three conditions are met:
• A and B refer to the same string (their addresses have the same string index)
• A’s initial position is greater than or equal to B’s initial position
• A’s final position is lesser than or equal to B’s initial position
To try this mode out, modify the schema used in the previous section as illustrated on figure 3 below.
Schema for testing the Count widget (Containing segmentation mode)
Figure 3: Schema for testing the Count widget (Containing segmentation mode).
The first instance of Segment produces a word segmentation (Regex: \w+ and Widget label: Words) which the second instance (the upper one) further decomposes into letters (Regex: \w and Widget label: Letters). The instance of Count is configured as shown on figure 4 below. The resulting table is the same as table 2 here (possibly with a different ordering of columns).
Interface of widget Count, Containing segmentation mode
Figure 4: Configuration of widget Count for counting letters in words.
Note that in this mode, checking the Merge contexts box still restricts counting to those units that are contained whithin the segments of another segmentation, but without treating each context type separately. In the case of letters whithin words, there is no difference between this mode and mode No context (see previous section). It does however make a difference in the case of letter bigram counting, because those bigrams that straddle a word boundary will be excluded in this case (contrary to what can be seen in table 1 here). | __label__pos | 0.997281 |
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up
Join the Stack Overflow community to:
1. Ask programming questions
2. Answer and help your peers
3. Get recognized for your expertise
I wish to determine when a point (mouse position) in on, or near a curve defined by a series of B-Spline control points.
The information I will have for the B-Spline is the list of n control points (in x,y coordinates). The list of control points can be of any length (>= 4) and define a B-spline consisting of (n−1)/3 cubic Bezier curves. The Bezier curves are are all cubic. I wish to set a parameter k,(in pixels) of the distance defined to be "near" the curve. If the mouse position is within k pixels of the curve then I need to return true, otherwise false.
Is there an algorithm that gives me this information. Any solution does not need to be precise - I am working to a tolerance of 1 pixel (or coordinate).
I have found the following questions seem to offer some help, but do not answer my exact question. In particular the first reference seems to be a solution only for 4 control points, and does not take into account the nearness factor I wish to define.
Position of a point relative to a Bezier curve
Intersection between bezier curve and a line segment
EDIT: An example curve:
e, 63.068, 127.26
29.124, 284.61
25.066, 258.56
20.926, 212.47
34, 176
38.706, 162.87
46.556, 149.82
54.393, 138.78
The description of the format is: "Every edge is assigned a pos attribute, which consists of a list of 3n + 1 locations. These are B-spline control points: points p0, p1, p2, p3 are the first Bezier spline, p3, p4, p5, p6 are the second, etc. Points are represented by two integers separated by a comma, representing the X and Y coordinates of the location specified in points (1/72 of an inch). In the pos attribute, the list of control points might be preceded by a start point ps and/or an end point pe. These have the usual position representation with a "s," or "e," prefix, respectively."
EDIT2: Further explanation of the "e" point (and s if present).
In the pos attribute, the list of control points might be preceded by a start point ps and/or an end point pe. These have the usual position representation with a "s," or "e," prefix, respectively. A start point is present if there is an arrow at p0. In this case, the arrow is from p0 to ps, where ps is actually on the node’s boundary. The length and direction of the arrowhead is given by the vector (ps −p0). If there is no arrow, p0 is on the node’s boundary. Similarly, the point pe designates an arrow at the other end of the edge, connecting to the last spline point.
share|improve this question
How are you working with the bezier curve? What are you writing an app for? Most of the time with UI elements you can define a mouseover or something, are you writing a UI element from scratch? What language? – jcolebrand Nov 25 '10 at 6:47
Cubic Bezier curve ALWAYS depends on exactly 4 control points. Maybe you want to make a en.wikipedia.org/wiki/Spline_(mathematics) from several curves or something? – skalee Nov 25 '10 at 10:55
@drachenstern I am effectively writing a UI element from scratch. I am writing an graphical editor, where the various elements of the editor are visual representations of the underlying objects and need to manipulate them in accordance with the rules governing the objects. – Chris Walton Nov 25 '10 at 15:25
@skalee - your answer made me look again at the definition of what I am working with. It is indeed a B-spline with n control points which define (n−1)/3 cubic Bezier curves. – Chris Walton Nov 25 '10 at 15:28
1
@Chris ufff sounds pretty convolved. I'll read it carefully and see what I can get. Thanks. – Dr. belisarius Nov 27 '10 at 1:50
up vote 9 down vote accepted
You may do this analitically, but a little math is needed.
A Bezier curve can be expressed in terms of the Bernstein Basis. Here I'll use Mathematica, that provides good support for the math involved.
So if you have the points:
pts = {{0, -1}, {1, 1}, {2, -1}, {3, 1}};
The eq. for the Bezier curve is:
f[t_] := Sum[pts[[i + 1]] BernsteinBasis[3, i, t], {i, 0, 3}];
Keep in mind that I am using the Bernstein basis for convenience, but ANY parametric representation of the Bezier curve would do.
Which gives:
alt text
Now to find the minimum distance to a point (say {3,-1}, for example) you have to minimize the function:
d[t_] := Norm[{3, -1} - f[t]];
For doing that you need a minimization algorithm. I have one handy, so:
NMinimize[{d[t], 0 <= t <= 1}, t]
gives:
{1.3475, {t -> 0.771653}}
And that is it.
HTH!
Edit Regarding your edit "B-spline with consisting of (n−1)/3 cubic Bezier curves."
If you constructed a piecewise B-spline representation you should iterate on all segments to find the minima. If you joined the pieces on a continuous parameter, then this same approach will do.
Edit
Solving your curve. I disregard the first point because I really didn't understand what it is.
I solved it using standard Bsplines instead of the mathematica features, for the sake of clarity.
Clear["Global`*"];
(*first define the points *)
pts = {{
29.124, 284.61}, {
25.066, 258.56}, {
20.926, 212.47}, {
34, 176}, {
38.706, 162.87}, {
46.556, 149.82}, {
54.393, 138.78}};
(*define a bspline template function *)
b[t_, p0_, p1_, p2_, p3_] :=
(1-t)^3 p0 + 3 (1-t)^2 t p1 + 3 (1-t) t^2 p2 + t^3 p3;
(* define two bsplines *)
b1[t_] := b[t, pts[[1]], pts[[2]], pts[[3]], pts[[4]]];
b2[t_] := b[t, pts[[4]], pts[[5]], pts[[6]], pts[[7]]];
(* Lets see the curve *)
Show[Graphics[{Red, Point[pts], Green, Line[pts]}, Axes -> True],
ParametricPlot[BSplineFunction[pts][t], {t, 0, 1}]]
. ( Rotated ! for screen space saving )
alt text
(*Now define the distance from any point u to a point in our Bezier*)
d[u_, t_] := If[(0 <= t <= 1), Norm[u - b1[t]], Norm[u - b2[t - 1]]];
(*Define a function that find the minimum distance from any point u \
to our curve*)
h[u_] := NMinimize[{d[u, t], 0.0001 <= t <= 1.9999}, t];
(*Lets test it ! *)
Plot3D[h[{x, y}][[1]], {x, 20, 55}, {y, 130, 300}]
This plot is the (minimum) distance from any point in space to our curve (of course the value over the curve is zero):
alt text
share|improve this answer
1
@Eric Nminimize can be replaced by any math library function able to minimize functions in one variable. There are hordes out there. The OP doesn't specify environment and language, so implementation details are useless. – Dr. belisarius Nov 25 '10 at 13:34
1
@belisarius: On the contrary, it's always useful to give more details about your answer. It makes it easier for others to try it out. – Eric Nov 25 '10 at 13:54
3
@Eric Finding function maxima and minima is a problem much studied in CS. Almost any CS curricula in the world covers it. If you feel in the mood to learn more about it just google "function maxima minimma algorithm" or peep at mathworld.wolfram.com/topics/MaximaandMinima.html or post a question in SO. This specific question is about Bezier curves and not general math. – Dr. belisarius Nov 25 '10 at 14:21
1
@Chris See edit "ANY parametric representation of the Bezier curve would do". I think you only need the minimization library function, you already have the rest – Dr. belisarius Nov 25 '10 at 15:56
1
@Chris Edited. Trying to solve the upload problem. – Dr. belisarius Nov 27 '10 at 4:23
First, render the curve to a bitmap (black and white) with your favourite algorithm. Then, whenever you need, determine the nearest pixel to the mouse position using information from this question. You can modify the searching function so that it will return distance, so you can easilly compare it with your requirements. This method gives you the distance with tolerance of 1-2 pixels, which will do, I guess.
share|improve this answer
doesn't this seem too brute forceish? – fortran Nov 25 '10 at 15:12
This is a different way of looking at my problem. I was focussed on an analytic approach, and had not considered this alternative. – Chris Walton Nov 25 '10 at 15:32
Definition: distance from a point to a line segment = distance from the original point to the closest point still on the segment.
Assumption: an algo to compute the distance from a point to a segment is known (e.g. compute the intercept with the segment of the normal to the segment passing through the original point. If the intersection is outside the segment, pick the closest end-point of the segment)
1. use the deCasteljau algo and subdivide your cubics until getting to a good enough daisy-chain of linear segments. Supplementary info the "Bezier curve flattening" section
2. consider the minimum of the distances between your point and the resulted segments as the distance from your point to the curve. Repeat for all the curves in your set.
Refinement at point 2: don't compute the actual distance, but the square of it, getting the minimum square distance is good enough - saves a sqrt call/segment.
Computation effort: empirically a cubic curve with a maximum extent (i.e. bounding box) of 200-300 results in about 64 line segments when flattened to a maximum tolerance of 0.5 (approx good enough for the naked eye).
1. Each deCasteljau step requires 12 division-by-2 and 12 additions.
2. Flatness evaluation - 8 multiplications + 4 additions (if using the TaxiCab distance to evaluate a distance)
3. the evaluation of point-to-segment distance requires at max 12 multiplications and 11 additions - but this will be a rare case in the context of Bezier flattening, I'd expect an average of 6 multiplications and 9 additions.
So, assuming a very bad case (100 straight segments/cubic), you finish in finding your distance with a cost of approx 2600 multiplications + 2500 additions per considered cubic.
Disclaimers:
1. don't ask me for a demonstration on the numbers in the computational effort evaluation above, I'll answer with "Use the source-code" (note: Java implementation).
2. other approaches may be possible and maybe less costly.
Regards,
Adrian Colomitchi
share|improve this answer
Your Answer
discard
By posting your answer, you agree to the privacy policy and terms of service.
Not the answer you're looking for? Browse other questions tagged or ask your own question. | __label__pos | 0.753519 |
50 short programs in Rust, #1
October 7, 2019
I'm at the point where I can read and write Rust (well, with a fair bit of help from the compiler), but I don't yet feel fluent in it and it doesn't feel completely natural. For example, I still reach for Python when I want to implement short programs to try out an idea.
I'd like to build my fluency in Rust by writing a lot of those programs - I've set a target of 50 - so that I improve my ability to write Rust quickly, and am aware of techniques and approaches for doing the sort of thing I want to do quickly. (Often these will be ports or reimplementations of programs I've previously written in Python.)
The one I'm going to start with is a program for accepting TCP connections and closing them immediately, and printing out a count of how many times it's done so. This can be quite useful for ferreting out bugs in TCP clients - if they have logic to reconnect when the connection drops, but don't have rate-limiting or delays on those connection attempts, this can trigger them to spin around connecting very fast and use a lot of CPU.
use std::net::TcpListener;
use std::time::SystemTime;
fn main() {
let listener =
TcpListener::bind("0.0.0.0:8006").expect("Could not bind to socket");
let mut conncount = 0;
let mut start = None;
// Loop over incoming connections so that we accept them, but don't assign
// them to a variable so that they immediately drop and are closed.
for _ in listener.incoming() {
conncount += 1;
// It's more useful to know the time since our first connection, not
// the time since the program started.
if start.is_none() {
start = Some(SystemTime::now());
}
let elapsed = start
.unwrap()
.elapsed()
.expect("Could not get elapsed time!");
println!(
"{} connections in {}.{} seconds",
conncount,
elapsed.as_secs(),
elapsed.subsec_millis()
);
}
}
This project is also on Github, at https://github.com/rkday/50-short-programs-in-rust. | __label__pos | 0.912329 |
1. Hey there Guest,
The game servers have moved to semi-dedicated hardware and IPs have changed. Please see front page server widget for up-to-date game server information.
Let's make TF2M some money: purchasable emoticons
Discussion in 'Site Discussion' started by ardysqrrl, Mar 16, 2011.
1. ardysqrrl
ardysqrrl L4: Comfortable Member
Messages:
173
Positive Ratings:
159
I've had this idea for a while but it really hit home when I wanted to post [IMG] on the void's stories thread
so this is a pretty simple idea: submit a png of some maximum size along with a cash donation (10-15 dollars is probably sufficient) and then the emoticon is added to the forums!
I'm aware that the forums support inline images but using emoticon codes is far more snazzy.
2. Fr0Z3nR
aa Fr0Z3nR Creator of blackholes & memes. Destroyer of forums
Messages:
6,391
Positive Ratings:
5,464
I'm not down for this, basically because I barely use emoticons... also I now notice that the forums have advertisments now inbetween some posts... which bugs me a little.
3. Bermuda Cake
Bermuda Cake L9: Fashionable Member
Messages:
679
Positive Ratings:
241
uh
4. tyler
aa tyler snail prince, master of a ruined tower
Messages:
5,035
Positive Ratings:
4,499
...does it?
edit: nvm im dumb i figured out why i dont see them
5. ardysqrrl
ardysqrrl L4: Comfortable Member
Messages:
173
Positive Ratings:
159
maybe if you bought more emoticons the forums wouldn't need to have ads
6. Fr0Z3nR
aa Fr0Z3nR Creator of blackholes & memes. Destroyer of forums
Messages:
6,391
Positive Ratings:
5,464
Or I could do what people normally do, which is get veep...
I think more perks for veep besides just upload/no adverts/server/veep would be better than micro transactions. Even though this is a TF2 community, lets not become TF2.
7. drp
aa drp
Messages:
2,256
Positive Ratings:
2,572
yep 2 more ad banners after 1st and last. sorry guys, but the servers need to be paid for.
8. Fr0Z3nR
aa Fr0Z3nR Creator of blackholes & memes. Destroyer of forums
Messages:
6,391
Positive Ratings:
5,464
I will get Veep soon... I have more money than I expected (*yay*) so another month or 2 will be in order....
I still think that more veep exclusive/alluring perks would be more benificial than micro-transactions in the TF2Maps.net Gift shop (see previous thread on avatar hats). Maybe make the expanded emoticons and avatar hats part of being a VIP... I think that with drp and the lotteries, those potentially will be good ways to get people to want to get VIP. It looks like we have a lot of newer mappers coming in now, so thats also good.
• Thanks Thanks x 1
9. A Boojum Snark
aa A Boojum Snark Toraipoddodezain Mazahabado
Messages:
4,769
Positive Ratings:
5,538
I'm pretty sure both of these suggestions by ardy have been tongue-in-cheek and not exactly serious. In case that has gone over some heads.
• Thanks Thanks x 1
10. Vincent
aa Vincent 🔨 Grandmaster Lizard Wizard Jedi 🔨
Messages:
914
Positive Ratings:
680
Can't really believe people don't notice him trolling.
11. ardysqrrl
ardysqrrl L4: Comfortable Member
Messages:
173
Positive Ratings:
159
it's not trolling :(
12. Vincent
aa Vincent 🔨 Grandmaster Lizard Wizard Jedi 🔨
Messages:
914
Positive Ratings:
680
A very bad joke sounds a bit less harsh I suppose.
13. ardysqrrl
ardysqrrl L4: Comfortable Member
Messages:
173
Positive Ratings:
159
okay I admit this one wasn't funny but I think people got a good laugh out of avatar hats
14. Fr0Z3nR
aa Fr0Z3nR Creator of blackholes & memes. Destroyer of forums
Messages:
6,391
Positive Ratings:
5,464
I did laugh at the hats...
Though, with the addition of the new adverts, it is hard to tell if this is or is not a joke.
15. Pocket
aa Pocket func_croc
Messages:
4,489
Positive Ratings:
2,377
I was thinking more of Something Awful's forum, which I don't believe charges extra for emoticons but charges for damn near everything else forum users usually take for granted.
16. Wilson
aa Wilson Burial by Sleep
Messages:
1,256
Positive Ratings:
938
We need hats for all these smileys, that is ALL we need, nothing more, nothing less.
17. ardysqrrl
ardysqrrl L4: Comfortable Member
Messages:
173
Positive Ratings:
159
SA charges 30 bucks if anybody wants to add a new emote and they're doing just fine
I think the greatest feature of SA though is the ability to purchase new avatars and title text for other people
18. LeSwordfish
aa LeSwordfish semi-trained quasi-professional
Messages:
4,115
Positive Ratings:
6,437
19. tyler
aa tyler snail prince, master of a ruined tower
Messages:
5,035
Positive Ratings:
4,499
20. ardysqrrl
ardysqrrl L4: Comfortable Member
Messages:
173
Positive Ratings:
159
is it that you don't have a credit card
| __label__pos | 0.625968 |
cancel
Showing results for
Search instead for
Did you mean:
Create Post
Net Admin Likes Candlelight Dinners, Good Conversation, and Long (SNMP) Walks
Level 14
OK, no, not really. No, we haven't changed the format here on thwack: though you can get some good conversation in our forums, no one is going to suggest the use of candles in your network closet. And this graphic just seems strangely appropriate, right now:
candlelight,communications,couples,food,laptop computers,men,online dating,people,restaurants,romantic dinner,technologies,waiters,women
You mean to say it's not "Data Night"?
All absolutely horrible joking aside, while doing some documentation maintenance the other day, I was reminded of a pretty cool little network management tool that I think we tend to take for granted around here: SolarWinds SNMPWalk (.zip). So, for those of you who don't already know, the question is, "What does it do?" Well, in short, by generating a map of the management information base (MIB) object IDs (OIDs) that correspond to specific types of information about any given device you want to monitor with SNMP, it helps you figure out what you can know about your network equipment. If that doesn't makes any sense, let's review a bit.
What is a MIB?
A Management Information Base (MIB) is the formal description of a set of objects that can be managed using SNMP. MIB-I refers to the initial MIB definition, and MIB-II refers to the current definition. Each MIB object stores a value such as sysUpTime, bandwidth utilization, or sysContact. During polling, SolarWinds NPM sends a SNMP GET request to each device to poll the specified MIB objects. Received responses are then recorded in the SolarWinds database for use in NPM, including within Orion Web Console resources.
All of which probably leads you to another question:
What is SNMP?
For most network monitoring and management tasks, NPM uses the Simple Network Management Protocol (SNMP). SNMP enabled network devices, including routers, switches, and PCs, host SNMP agents that maintain a virtual database of system status and performance information that is tied to specific Object Identifiers (OIDs). This virtual database is referred to as a Management Information Base (MIB), and NPM uses MIB OIDs as references to retrieve specific data about a selected, SNMP enabled, managed device. Access to MIB data may be secured either with SNMP Community Strings, as provided with SNMPv1 and SNMPv2c, or with optional SNMP credentials, as provided with SNMPv3.
Notes:
• To properly monitor devices on your network, you must enable SNMP on all devices that are capable of SNMP communications. The steps to enable SNMP differ by device, so you may need to consult the documentation provided by your device vendor.
• If SNMPv2c is enabled on a device you want NPM to monitor, by default, NPM will attempt to use SNMPv2c to poll the device for performance information. If you only want NPM to poll using SNMPv1, you must disable SNMPv2c on the device to be polled.
• Most network devices can support several different types of MIBs. While most devices support the standard MIB-II MIBs, they may also support any of a number of additional MIBs that you may want to monitor. Using a fully customizable Orion Universal Device Poller, you can gather information from virtually any MIB on any network device to which you have access.
So, Let's Go For a Walk
Which brings us back to the SolarWinds SNMPWalk (.zip). Download and run it. Point it at a device on your network, and it will generate a list of all available OIDs for monitoring with SNMP. If NPM doesn't already recognize your device and monitor its OIDs automatically, you can create your own Universal Device Poller (UnDP) to give you the data you so desperately crave. For more information about working with a UnDP, see "Monitoring MIBs with Universal Device Pollers" in the SolarWinds Orion NPM Administrator Guide. With SNMP, the MIB, NPM, and UnDPs you can monitor just about anything, hardware-wise. Yes, it's all pretty sweet, but, no matter the price, it's still probably not a good gift for your pretty sweetie...OK, I'm leaving now; no more jokes, I promise...
1 Comment
Level 9
Best discussion name EVER!!! | __label__pos | 0.543864 |
Diese Präsentation wurde erfolgreich gemeldet.
Wir verwenden Ihre LinkedIn Profilangaben und Informationen zu Ihren Aktivitäten, um Anzeigen zu personalisieren und Ihnen relevantere Inhalte anzuzeigen. Sie können Ihre Anzeigeneinstellungen jederzeit ändern.
Geometry
1.048 Aufrufe
Veröffentlicht am
Veröffentlicht in: Bildung
• Als Erste(r) kommentieren
• Gehören Sie zu den Ersten, denen das gefällt!
Geometry
1. 1. GEOMETRY 1
2. 2. Recap Geometrical Terms An exact location on Point a plane is called a point. A straight path on a Line plane, extending in both directions with no endpoints. A part of a line that Line has two endpointssegment and thus has a definite length. A line segment extended Ray indefinitely in one direction
3. 3. POINTS Points are location without substance. They have neither size nor dimension. Points are imperfectly represented on the page by a small dot. A capital letter is used to name a point as we see labeled below. A 3
4. 4. POINTS You have seen points before in the xy- coordinate plane. They are represented by ordered pairs of numbers (x, y). Two intersecting lines intersect in a point. Points make up every geometric figure. For example, string a bunch of them together and you have a line. 4
5. 5. LINES When we talk about lines in geometry we are talking about straight lines that extend forever in both directions. They never end. Below is a picture of a line. When we draw a line we put arrows on the ends to signify that the line keeps going. 5
6. 6. LINES There are two ways to name a line. One way is to use a lowercase letter (usually l, m, n, p, q, r, s, or t) as in the figure below. m 6
7. 7. LINES Two points determine a line, right? Right. What we mean by this is that if you have two different points, there is one and only one line that passes through them. Because of this, another way to name a line is by using two points on the line. Picture of Line Name of Line B A or AB BA 7
8. 8. LINES So, to name a line by using two points, we write the two capital letters of the points next to each other and then draw a little line symbol over them. It doesn’t matter which letter comes first. Important: the line symbol above the letters has arrows on both ends. AB 8
9. 9. LINE SEGMENTS Line segments are straight and they have two endpoints. Line segments come in various lengths. Line segments are parts of lines. Below is a picture of a line segment. When we draw one, we usually use dots to emphasize the endpoints. 9
10. 10. LINE SEGMENTS There is only one way we will name line segments. We name them by using their endpoints. A Picture Name or BA B AB 10
11. 11. LINE SEGMENTS When naming a line segment we draw a picture of a line segment (without arrows or dots on the ends) above the two capital letters denoting the endpoints. Note well the difference between the name of a line and the name of a line segment: Line Line Segment AB AB 11
12. 12. RAYS A ray is straight and it has one endpoint. A ray extends forever in one direction. Imagine a line (not a line segment). If you break the line into two pieces, each piece will be a ray. Below is a picture of a ray. We draw an arrow on one end and a dot on the other end. endpoint 12
13. 13. RAYS We name a ray by using its endpoint and any other point on the ray. We always write the endpoint first, then the other point, and then we draw a picture of a ray above the letters. Picture Name C D CD 13
14. 14. What Is An Angle ?When two non-collinear rays join with a common endpoint (origin) an angle is formed. Ray BA A Common B endpoint B C Ray BCCommon endpoint is called the vertex of the angle. Ray BA and BC are two non-collinear raysRay BA and ray BC are called the arms of ABC.
15. 15. ANGLES An angle is what you get when you take two rays pointing in different directions and join them at their endpoints. The angle below is formed from the rays BA and BC. A B C 15
16. 16. Types Of Angles There are four main types of angles.Right Acute angle Obtuse angleangleA A AB C B B C C Straight angle A B C
17. 17. WHAT IS A RIGHT ANGLE?A right angle is an Right angle angle that measures 90 degrees and forms a square.
18. 18. WHAT IS AN ACUTE ANGLE? Acute angle An angle that measures less than 90 degrees. “A cute little angle”
19. 19. WHAT IS AN OBTUSE ANGLE? Obtuse angle An obtuse angle is an angle that measures more than 90 degrees.
20. 20. STRAIGHT ANGLE Straight angle: An angle whose Straight angle measure is 180 degrees A B C A straight angle changes the direction to point the opposite way. It looks like a straight line. 20
21. 21. 21
× | __label__pos | 0.989513 |
UGameplayStatics::PlaySoundAtLocation
Plays a sound at the given location.
Choose your operating system:
Windows
macOS
Linux
References
Module
Engine
Header
/Engine/Source/Runtime/Engine/Classes/Kismet/GameplayStatics.h
Include
#include "Kismet/GameplayStatics.h"
Source
/Engine/Source/Runtime/Engine/Private/GameplayStatics.cpp
Syntax
static void PlaySoundAtLocation
(
const UObject * WorldContextObject,
USoundBase * Sound,
FVector Location,
FRotator Rotation,
float VolumeMultiplier,
float PitchMultiplier,
float StartTime,
class USoundAttenuation * AttenuationSettings,
USoundConcurrency * ConcurrencySettings,
const AActor * OwningActor,
UInitialActiveSoundParams * InitialParams
)
Remarks
Plays a sound at the given location. This is a fire and forget sound and does not travel with any actor. Replication is also not handled at this point.
Parameters
Parameter
Description
Sound
sound to play
Location
World position to play sound at
Rotation
World rotation to play sound at
VolumeMultiplier
A linear scalar multiplied with the volume, in order to make the sound louder or softer.
PitchMultiplier
A linear scalar multiplied with the pitch.
StartTime
How far in to the sound to begin playback at
AttenuationSettings
Override attenuation settings package to play sound with
ConcurrencySettings
Override concurrency settings package to play sound with
OwningActor
The actor to use as the "owner" for concurrency settings purposes. Allows PlaySound calls to do a concurrency limit per owner. | __label__pos | 0.882675 |
Salesforce DevOps? The Role of Automation in Streamlining DevOps
In the rapidly evolving landscape of software development, the integration of DevOps practices has become indispensable, particularly in the realm of Salesforce development. One of the key pillars underpinning successful Salesforce DevOps implementation is automation. This article explores the pivotal role of automation in streamlining Salesforce DevOps processes, facilitating efficiency, reliability, and agility in software delivery. – Salesforce DevOps Online Training
Understanding the Significance of Automation:
Automation lies at the heart of DevOps methodology, acting as a catalyst for accelerating development cycles, enhancing collaboration, and ensuring consistent, high-quality deployments.
In the context of Salesforce DevOps, automation extends across various stages of the development lifecycle, from code compilation and testing to deployment and monitoring
By leveraging automation tools such as Jenkins, CircleCI, or Salesforce DX CLI, organizations can automate the compilation, packaging, and deployment of Salesforce metadata, reducing manual errors and expediting the release cycle. – Salesforce DevOps Online Courses
Automated Testing and Quality Assurance:
Continuous Integration and Continuous Delivery (CI/CD): Automation enables the seamless orchestration of CI/CD pipelines, allowing for the continuous integration of code changes and the automated deployment of new features or enhancements. By automating code integration, testing, and deployment tasks, organizations can achieve shorter release cycles, rapid feedback loops, and greater agility in responding to market demands. – Salesforce DevOps Training in Ameerpet
Automated Environment Provisioning and Configuration:
Managing Salesforce environments efficiently is crucial for enabling parallel development, testing, and staging activities.
Automation tools like Terraform or Salesforce Environments allow organizations to automate the provisioning and configuration of sandbox environments, ensuring consistency and reproducibility across different stages of the development pipeline.
Automated Monitoring and Performance Management: Proactive monitoring and performance management are essential for ensuring the stability and scalability of Salesforce applications.
Automation tools such as Salesforce Event Monitoring, Splunk, or New Relic enable organizations to automate the collection, analysis, and visualization of key performance metrics, facilitating real-time insights and timely interventions.
Conclusion:
In the realm of Salesforce DevOps, automation serves as a linchpin for streamlining development processes, enhancing collaboration, and driving innovation. By embracing automation across various facets of the development lifecycle, organizations can achieve greater efficiency, reliability, and agility in delivering high-quality Salesforce solutions. As the demand for accelerated software delivery continues to rise, automation remains paramount in realizing the full potential of Salesforce DevOps initiatives.
Visualpath Teaching the best Salesforce DevOps Training. It is the NO.1 Institute in Hyderabad Providing Salesforce DevOps Online Training Institute. Our faculty has experience in real-time and provides DevOps Real-time projects and placement assistance.
Vocational Education Improves Employability
In the rapidly evolving job market, the search for a lucrative job often comes down to one crucial factor, which is employability. Employability refers to the combination of skills, knowledge, and personal attributes that make an individual a desirable and effective employee. With the rapid transformation of industries and the emergence of new technologies, the importance of traditional academic qualifications is being complemented by the rising significance of vocational education.
Vocational training doesn’t just equip individuals with hands-on skills relevant to particular industries but also amplifies their potential for employment in various ways. It holds a crucial role in improving employability by providing individuals with specific skills, knowledge, and real-world exposure, which are necessary to thrive across various industries.
Here are several ways through which vocational education contributes to enhanced employability:
Targeted skill acquisitionVocational education is popular for its focus on practical skills acquisition. Unlike traditional academic paths that might encompass a wide range of subjects, vocational programs are designed to provide specific skills customized to particular industries or job roles. This targeted approach ensures that graduates are job-ready from day one.
Moreover, this focused skill acquisition gives graduates a competitive edge in job interviews and allows them to seamlessly integrate into the workforce which certainly positively impacts their employability.
Alignment with industry needsAnother significant advantage of vocational education is its ability to align with industry needs in real-time. Industries are evolving faster than ever due to technological advancements, and employers are seeking individuals who possess the most relevant and up-to-date skills.
Institutions offering vocational education often collaborate closely with industry partners to develop curricula that reflect the latest trends and requirements. This ensures that graduates are equipped with the skills that are currently in demand, making them attractive candidates to potential employers.
Practical problem-solvingVocational education emphasises practical problem-solving. Students learn not just by rote learning but by actively engaging with real-world challenges. This hands-on approach promotes a deeper understanding of the subject matter and enhances critical thinking abilities. Graduates of vocational programs are adept at tackling active challenges creatively and efficiently.
Employers value individuals who can think immediately and contribute solutions that drive business outcomes. Consequently, vocational education nurtures this skill set, making the graduates invaluable assets to prospective employers.
Soft skills and personal developmentWhile technical skills are dominant, vocational education also recognises the importance of soft skills and personal development. Communication, teamwork, adaptability, and time management are just a few examples of soft skills that employers highly value.
Vocational programs often incorporate opportunities for students to enhance these skills, either through group projects, presentations, or simulated workplace scenarios. These experiences not only make graduates more effective team players but also improve their ability to navigate complex work environments.
Internships and industry exposureMany vocational education programs include mandatory internships or work placements. These practical experiences not only provide students with a taste of the real working world but also allow them to apply their acquired skills in practical settings. Internships offer a platform to network, learn from experienced professionals, and gain insights into the industry’s day-to-day operations.
This exposure to the industry not only enhances technical skills but also provides a better understanding of workplace dynamics, protocols, and expectations. Graduates who have completed internships during their vocational education are better equipped to transition smoothly into full-time roles, increasing their employability.
Diversity of career pathwaysVocational education opens up a diverse range of career pathways. Vocational programs provide an alternative route to success as everyone’s strengths don’t lie in traditional academic subjects. From culinary arts to healthcare to construction, vocational education caters to a wide array of interests and talents.
This diversity ensures that individuals can pursue careers that resonate with their passion and strengths, ultimately leading to greater job satisfaction and commitment. When employees are engaged in their work, they tend to excel, positively impacting their long-term employability.
Contribution of vocational education to improving employability is significantVocational education significantly contributes to improving employability by imparting targeted skills, aligning with industry needs, developing practical problem-solving abilities, enhancing soft skills, providing real-world exposure, and offering diverse career pathways.
As the employment landscape continues to evolve, the role of vocational education in equipping individuals with the necessary tools to succeed in their chosen fields becomes even more critical. The synergy between vocational training and industry requirements creates a win-win situation for both graduates and employers, ensuring a well-prepared, adaptable, and job-ready workforce.
Living-smartly.com is a website that publishes information on a variety of topics including ancient Indian artisan vocational education, 64 kala or chausat kala. Overall, Sanathana dharma and Hindu dharma serves well in focus is on the right conduct including self-discipline, self-control, cultivating wisdom, and common ethics. Living Smartly also has published practical health articles like tomato and spinach side effects and diabetic diet plan for South Indians. Further, it provides smart tips & insights that covers all aspects of daily living such as health, philosophy, social skills, technology and wellness.
Testing Tools Course
In today’s rapidly evolving technological landscape, the demand for skilled professionals adept in testing tools has skyrocketed. As industries increasingly rely on software solutions to streamline operations, ensure quality, and enhance user experiences, the need for robust testing methodologies and tools has become paramount. A comprehensive course on testing tools serves as a gateway for individuals seeking to master the intricacies of software testing, equipping them with the knowledge and skills required to excel in this dynamic field.This immersive course delves deep into the fundamentals of software testing, laying a solid foundation for understanding its importance in the software development lifecycle. Participants will explore the various testing techniques and methodologies employed to detect defects, ensure functionality, and validate the performance of software applications across diverse platforms and environments.Central to this course is the exploration of a myriad of testing tools designed to streamline the testing process and enhance efficiency. Participants will gain hands-on experience with a wide array of tools, ranging from automated testing frameworks to performance testing solutions. Through practical exercises and real-world simulations, participants will learn how to leverage these tools effectively to expedite testing cycles, identify vulnerabilities, and optimize software quality.The course covers popular automated testing tools such as Selenium, Appium, and TestComplete, empowering participants to automate test cases across web, mobile, and desktop applications. Participants will learn how to create robust test scripts, execute test suites, and generate comprehensive test reports using these tools, thereby accelerating the testing process and minimizing manual intervention.Furthermore, participants will delve into the realm of performance testing, where they will explore tools like JMeter and LoadRunner to assess the scalability, reliability, and responsiveness of software applications under varying load conditions. Through hands-on exercises, participants will learn how to design realistic load scenarios, execute performance tests, and analyze key performance metrics to optimize application performance and scalability.In addition to automated and performance Testing Tools Course, participants will also gain exposure to a range of specialized testing tools tailored to specific domains and technologies. Whether it’s security testing tools like Burp Suite and OWASP ZAP for identifying and mitigating security vulnerabilities or API testing tools like Postman and SoapUI for testing web services, this course covers a diverse spectrum of tools essential for comprehensive software testing.Moreover, participants will learn about the latest trends and advancements in the field of testing tools, including the integration of artificial intelligence and machine learning techniques to enhance test automation and predictive analytics for proactive defect management.By the end of this course, participants will emerge as proficient testing professionals equipped with the knowledge, skills, and hands-on experience necessary to excel in today’s competitive job market. Whether aspiring to pursue a career as a software tester, quality assurance engineer, or automation architect, this course provides the essential tools and expertise to thrive in the ever-evolving landscape of software testing. | __label__pos | 0.805534 |
Release Candidate in the context of WordPress
A Release Candidate in the context of WordPress is a significant milestone in the software development process leading up to the final release of a new version of WordPress. It is an essential phase that allows developers and the community to thoroughly test the upcoming release before it is officially launched to the public. The term “Release Candidate” (RC) signifies that the development team believes the software is feature-complete and relatively stable, but it still requires rigorous testing to identify and fix any remaining bugs or issues.
During the WordPress development cycle, there are multiple pre-release stages, such as Alpha and Beta versions, where new features and enhancements are gradually added and tested by the development community. Once the development team feels that the software has reached a certain level of stability and all intended features have been included, they create the Release Candidate.
Release Candidates are typically made available to a broader audience, including developers, theme and plugin authors, and users willing to participate in the testing process. This wider testing ensures that the software is exposed to a diverse range of environments, configurations, and usage scenarios, helping to uncover any hidden issues that might not have been apparent during internal testing.
WordPress Release Candidates are not intended for production use, as they may still contain undiscovered bugs or compatibility problems with certain configurations. Users are encouraged to test the Release Candidates on non-production sites and report any issues they encounter to the WordPress development team. This feedback is invaluable, as it helps the team identify and fix bugs, refine features, and improve overall stability and performance before the final release.
Testing a Release Candidate involves various aspects of WordPress, including core functionality, themes, plugins, and compatibility with different hosting environments. Community members actively participate in testing, known as “testing parties,” organized by local WordPress communities or virtually across the globe.
The development team diligently addresses issues reported during the Release Candidate testing phase and prepares subsequent Release Candidates if necessary. Once the team is confident that the software is stable and any critical issues have been resolved, they proceed with the official release.
In summary, a Release Candidate in the context of WordPress is a crucial stage in the software development process. It allows for extensive community testing and feedback, ensuring that the final release is as stable, secure, and reliable as possible. By actively participating in testing and providing feedback during the Release Candidate phase, the WordPress community plays a pivotal role in shaping the platform’s future and maintaining its reputation as a robust and user-friendly content management system.
Pokud mi chcete napsat rychlou zprávu, využije, prosím, níže uvedený
kontaktní formulář. Děkuji.
Další Kontaktní údaje | __label__pos | 0.820077 |
ddwrt make wrt54g a client to use as a wireless nic
Discussion in 'DD-WRT Firmware' started by mesu55, Oct 11, 2006.
1. mesu55
mesu55 Network Guru Member
Hi,
I must be missing something. I want to wire my pc to my wrt54g (lan port) and allow it (wrt54g) to act like a wireless nic. (no wan port used) It will connect to an AP just like a wireless card would.
My pc would use IP like 192.168.1.12.or allow the router to assign one in this range. wrtg4g use auto dhcp which the wireless side picks up from the networks AP. like in a hotel. My pc would then be able to connect through their AP to the internet and I would hace a good wireless nic that I can set away from my pc into a good connect area such as a window.
I thought this was what client mode did but the info I am able to find seems this may not be the case.
Is it possible to have my wrt54g act like a wireless NIC?
If so are the any steps archived to explain how?
Thanks for any help.
mesu
2. __spc__
__spc__ Network Guru Member
3. mesu55
mesu55 Network Guru Member
Thanks,
I will read it and give it a try.
Mesu
4. __spc__
__spc__ Network Guru Member
1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.
Dismiss Notice | __label__pos | 0.809693 |
Ask Question
31 August, 20:10
A passenger train and a freight train leave San Jose at 3PM, traveling in the same direction. The passenger train is going three times as fast as the freight train. At 6PM they are 240 miles apart. How fast is each travelling?
+5
Answers (1)
1. 31 August, 22:51
0
The passenger train is going 120MPH and the freight train is traveling 40MPH
Know the Answer?
Not Sure About the Answer?
Get an answer to your question ✅ “A passenger train and a freight train leave San Jose at 3PM, traveling in the same direction. The passenger train is going three times as ...” in 📙 Mathematics if there is no answer or all answers are wrong, use a search bar and try to find the answer among similar questions.
Search for Other Answers | __label__pos | 0.900217 |
+7(983)178-57-68
Новые горизонты успешного бизнеса!
Главная Посчитать и заказатьОставить заявку Статьи Отзывы Контакты
Свойства текста
В их состав входят свойства выравнивания такие, как text-align и word-spacing, а также свойства изменения стиля text-decoration и text-shadow.
text-indent
Определяет длину отступа в первой строке блока.
.text{text-indent:15pt;}
text-align
Определяет выравнивание текста в элементе
- left - выравнивание по левому краю.
- center - выравнивание по центру.
- right - выравнивание по правому краю.
- justify - выравнивание по обоим краям (по ширине).
- inherit - применяется значение родительского элемента.
.text{text-align: justify;}
text-decoration
Определяет оформление текста.
- none - отсутствие элементов оформления (по умолчанию).
- underline - подчеркивание.
- overline - линия над текстом.
- line-through - перечеркивание.
- blink - мерцание.
- inherit - применяется значение родительского элемента.
.text{text-decoration: none;}
text-transform
Автоматически переводит в тексте буквы в верхний (нижний) регистр.
- none - отсутствие изменения регистра (по умолчанию).
- capitalize - переводит первую букву каждого слова в верхний регистр.
- uppercase - переводит все буквы в верхний регистр.
- lowercase -переводит все буквы в нижний регистр.
- inherit - применяется значение родительского элемента.
.text{text-transform: capitalize;}
text-shadow
Определяет значения, устанавливающие эффект затенения текста. Можно использовать несколько значений через запятую
.text{
text-shadow: 8px 8px 2px rgba(150, 150, 150, 1),
0 0 10px rgba(255, 255, 255, 1);
}
Первое значение - смещение тени по горизонтали относительно текста. Положительное значение этого параметра задает сдвиг тени вправо, отрицательное — влево. Обязательный параметр. Второе значение - смещение тени по вертикали относительно текста. Положительное значение этого параметра задает сдвиг тени вправо, отрицательное — влево. Третье значение - радиус размытия тени. Четвертое - цвет
letter-spacing
Определяет интервал между символами текста.
- none - интервал, обычные для используемого шрифта.
- inherit - применяется значение родительского элемента.
.text{letter-spacing: 5px;}
word-spacing
Определяет интервал между словами.
- none - интервал, обычный для используемого шрифта.
- inherit - применяется значение родительского элемента.
.text{word-spacing: 2px;}
white-space
Определяет, как обрабатывать пробелы.
- normal - пробелы сворачиваются, если это необходимо для размещения элемента. Этот способ, который использует HTML по умолчанию
- pre - пробелы обрабатываются так, как указано в коде (предварительно отформатированный текст).
- nowrap - сворачиваются все пробелы.
- inherit - применяется значение родительского элемента.
.text{white-space: pre;}
Остались вопросы? Спрашивайте!
Понравилась статья? Расскажи другим :)
Опубликовано: | Просмотров: 3790 | __label__pos | 0.907073 |
• Post Reply Bookmark Topic Watch Topic
• New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Jeanne Boyarsky
• Ron McLeod
• Paul Clapham
• Liutauras Vilda
Sheriffs:
• paul wheaton
• Rob Spoor
• Devaka Cooray
Saloon Keepers:
• Stephan van Hulst
• Tim Holloway
• Carey Brown
• Frits Walraven
• Tim Moores
Bartenders:
• Mikalai Zaikin
Why are write calls blocking?
Ranch Hand
Posts: 84
• Mark post as helpful
• send pies
Number of slices to send:
Optional 'thank-you' note:
• Quote
• Report post to moderator
It's obvious why a read on an InputStream can block, but why would a write to an OutputStream block? The only scenario I can think of is when you're requesting writing at a faster rate than the station's network upload rate. Is that correct? What are there other reasons?
Marshal
Posts: 28260
95
Eclipse IDE Firefox Browser MySQL Database
• Mark post as helpful
• send pies
Number of slices to send:
Optional 'thank-you' note:
• Quote
• Report post to moderator
What's the point of enumerating possible reasons?
Anyway a write will always block for a short period of time because nothing happens instantaneously. You only really care if it affects the throughput of your application badly enough to cause a problem. And does it?
Bartender
Posts: 6109
6
Android IntelliJ IDE Java
• Mark post as helpful
• send pies
Number of slices to send:
Optional 'thank-you' note:
• Quote
• Report post to moderator
marwen Bakkar wrote:It's obvious why a read on an InputStream can block, but why would a write to an OutputStream block? The only scenario I can think of is when you're requesting writing at a faster rate than the station's network upload rate. Is that correct? What are there other reasons?
It's just like any other operation you perform: You invoke the method, and when it's done, it returns. It's a synchronous operation, just like any others are unless steps are taken to make them otherwise (i.e., multirhreading).
marwen Bakkar
Ranch Hand
Posts: 84
• Mark post as helpful
• send pies
Number of slices to send:
Optional 'thank-you' note:
• Quote
• Report post to moderator
Paul Clapham wrote:What's the point of enumerating possible reasons?
Anyway a write will always block for a short period of time because nothing happens instantaneously. You only really care if it affects the throughput of your application badly enough to cause a problem. And does it?
Consider a chat server that's constantly broadcasting messages to multiple clients using TCP. The server has a message queue from which a dispatcher thread polls messages and dispatches them to the clients. During the iteration on the client list, if one iteration gets stuck on writing then service time suffers for the rest of the list. I need to know why and how often would that happen.
Ranch Hand
Posts: 124
• Mark post as helpful
• send pies
Number of slices to send:
Optional 'thank-you' note:
• Quote
• Report post to moderator
Write calls block because the receiver of the data you are writing to is not ready to receive the data.
For instance, when writing to file, the operating system needs time to get/create the file before populating it with data.
Similarly, in TCP/IP, the process that is receiving your data needs to be "listening" to your data before your write can proceed. In such a case, if you find that your writing process blocks infinitely, you can know for sure that you need to revise your communication protocol between your write and read process. In a way, blocking also helps in debugging communication protocol related errors.
Just my 2 cents. ;)
Paul Clapham
Marshal
Posts: 28260
95
Eclipse IDE Firefox Browser MySQL Database
• Mark post as helpful
• send pies
Number of slices to send:
Optional 'thank-you' note:
• Quote
• Report post to moderator
marwen Bakkar wrote:I need to know why and how often would that happen.
It isn't possible to answer the question "how often" for a hypothetical server running on an unknown network with an unknown number of clients. Even if you knew all of those things in detail you still wouldn't be able to predict how often it would happen. If you have to know everything in advance then perhaps network processing is not for you.
marwen Bakkar
Ranch Hand
Posts: 84
• Mark post as helpful
• send pies
Number of slices to send:
Optional 'thank-you' note:
• Quote
• Report post to moderator
Yeah I know it's hard to answer and I have no means to test it because I'd need a real world scenario with actual users on my server. I thought if I could figure out the reasons that could cause it maybe I would have some insight as to how likely it will occur.
This is related to an important design decision in a project I'm working on. If it's not uncommon for a write on a socket to block for a significant time, then to avoid bad service time for subsequent sockets in the loop maybe it would be better to use Async IO in release 1.7, which allows you to request a write operation and move on. That way a slow write operation doesn't hurt what comes next. Do you know any reliable open source chat server I can look at?
marwen Bakkar
Ranch Hand
Posts: 84
• Mark post as helpful
• send pies
Number of slices to send:
Optional 'thank-you' note:
• Quote
• Report post to moderator
To answer the question, It turns out the solution is simple with NIO. try to write in non blocking mode, if it succeeds we're done. If not, see how many bytes have been written and queue the bytes that haven't. Subscribe to write readiness for the channel. When it is, write the queue. I saw this in the kryonet library.
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
Bookmark Topic Watch Topic
• New Topic | __label__pos | 0.989357 |
Source code for galaxy.security.passwords
import hashlib
from base64 import b64encode
from os import urandom
from galaxy.util import (
safe_str_cmp,
smart_str,
unicodify
)
SALT_LENGTH = 12
KEY_LENGTH = 24
HASH_FUNCTION = 'sha256'
COST_FACTOR = 100000
[docs]def hash_password(password): """ Hash a password, currently will use the PBKDF2 scheme. """ if password is None: raise Exception("password cannot be None") return hash_password_PBKDF2(password)
[docs]def check_password(guess, hashed): """ Check a hashed password. Supports either PBKDF2 if the hash is prefixed with that string, or sha1 otherwise. """ if hashed.startswith("PBKDF2"): if check_password_PBKDF2(guess, hashed): return True else: # Passwords were originally encoded with sha1 and hexed if safe_str_cmp(hashlib.sha1(smart_str(guess)).hexdigest(), hashed): return True # Password does not match return False
[docs]def hash_password_PBKDF2(password): # Generate a random salt salt = b64encode(urandom(SALT_LENGTH)) # Apply the pbkdf2 encoding hashed_password = pbkdf2_bin(password, salt, COST_FACTOR, KEY_LENGTH, HASH_FUNCTION) encoded_password = unicodify(b64encode(hashed_password)) # Format return 'PBKDF2${}${}${}${}'.format(HASH_FUNCTION, COST_FACTOR, unicodify(salt), encoded_password)
[docs]def check_password_PBKDF2(guess, hashed): # Split the database representation to extract cost_factor and salt name, hash_function, cost_factor, salt, encoded_original = hashed.split('$', 5) # Hash the guess using the same parameters hashed_guess = pbkdf2_bin(guess, salt, int(cost_factor), KEY_LENGTH, hash_function) encoded_guess = unicodify(b64encode(hashed_guess)) return safe_str_cmp(encoded_original, encoded_guess)
[docs]def pbkdf2_bin(data, salt, iterations=COST_FACTOR, keylen=KEY_LENGTH, hashfunc=HASH_FUNCTION): """Returns a binary digest for the PBKDF2 hash algorithm of `data` with the given `salt`. It iterates `iterations` time and produces a key of `keylen` bytes. By default SHA-256 is used as hash function, a different hashlib `hashfunc` can be provided. """ data = smart_str(data) salt = smart_str(salt) return hashlib.pbkdf2_hmac(hashfunc, data, salt, iterations, keylen) | __label__pos | 0.998677 |
GEThttps://api.spotinst.io/aws/costs?accountId={ACCOUNT_ID}&fromDate={FROM_DATE}&toDate={TO_DATE}&aggregationPeriod={AGGREGATION_PERIOD}
Retrieve costs per specified account over a specified time period.
Example of URL with with daily aggregation period over a time period of 30 days:
https://api.spotinst.io/aws/ec2/account/costs?fromDate=1585699200000&toDate=1588291199000&aggregationPeriod=daily
Parameter Type Description
ACCOUNT_ID String
The account from which to retrieve financial information.
Example: act-12345
Default: The default account
FROM_DATE String
Date can be either in ISO-8601 date format (yyyy-mm-dd) or in Unix Timestamp format (e.g. 1494751821472).
Example: 2018-06-20
TO_DATE String
Date can be either in ISO-8601 date format (yyyy-mm-dd) or in Unix Timestamp format (e.g. 1494751821472).
Example: 2018-11-20
AGGREGATION_PERIOD String
Optional. The time period over which data is aggregated. Can only be "daily". For example, the figures in each data set are per day.
Example: daily
Request
Headers
Copied!
Downloaded!
{
"Content-Type": "application/json",
"Authorization": "Bearer ${token}"
}
Response - Example 1: Get Costs without Aggregation Period
Headers
Copied!
Downloaded!
{
"Content-Type": "application/json"
}
Body
Copied!
Downloaded!
{
"request": {
"id": "8ce51c56-6971-4783-8e15-b92438f7a65d",
"url": "/aws/costs",
"method": "GET",
"timestamp": "2015-07-06T11:44:27.963Z"
},
"response": {
"status": {
"code": 200,
"message": "OK"
},
"kind": "spotinst:aws:costs",
"items": [
{
"spot": {
"runningHours": "1470.80",
"actualCosts": "107.30",
"potentialCosts": "378.41",
"savingsPercentage": "71.64"
}
}
],
"count": 1
}
}
Response - Example 2: Get Costs with Daily Aggregation Period
Headers
Copied!
Downloaded!
{
"Content-Type": "application/json"
}
Body
Copied!
Downloaded!
{
"response": {
"status": {
"code": 200,
"message": "OK"
},
"kind": "spotinst:aws:costs",
"items": [
{
"timestamp": "2020-03-06T00:00:00.000Z",
"spot": {
"runningHours": "1470.80",
"actualCosts": "107.30",
"potentialCosts": "378.41",
"savingsPercentage": "71.64"
}
},
{
"timestamp": "2020-03-07T00:00:00.000Z",
"spot": {
"runningHours": "1470.80",
"actualCosts": "107.30",
"potentialCosts": "378.41",
"savingsPercentage": "71.64"
}
}
],
"count": 1
}
} | __label__pos | 0.977102 |
Design for a global market
Windows is used worldwide, in a variety of different markets and by customers who vary in culture, geographical region, or language. Follow these guidelines when designing your app, and you will be able to adapt it later for additional cultures, regions, and languages in the global market.
Introduction to world readiness
Many app developers create their apps thinking only of their own language and culture. When the app begins to grow into other languages and markets, it can be difficult to adapt the app. Text and image resources might be specified directly within the code, making it difficult to translate and prepare for other cultures. This process can be simplified by taking a few things into account when the app is first designed.
App design guidelines
These are guidelines to keep in mind as you design your app for a global market.
• Increase horizontal and vertical space for labels and text.
Some languages require a design layout with extra space for text longer than what is needed for English. Avoid fixed-width items and allow for wrapping text if possible. Some characters often seen in other languages include marks above or below what is typically used in English (such as Å or Ņ). Use the standard font sizes and line heights to provide adequate vertical space. Be aware that fonts for other languages may require larger minimum font sizes to remain legible.
• Use labels and text consistently.
Create a single string of text to convey a concept that can be used in multiple places in an app, such as a user instruction or an error message. Placing that string in a resource file results in it being translated only once, and reduces variations in its presentation. For info about creating resource files, see Defining app resources.
• Avoid colloquialisms and metaphors.
Such concepts are usually specific to a single language, and can be specific to a demographic within a language. If you are adopting an informal voice or tone, be sure to explain this for your translators. To learn how to comment your strings, see Defining app resources.
• Do not use technical jargon, abbreviations, or acronyms.
These are difficult to translate, and are not useful to non-technical audiences.
• Avoid culture-specific text or images.
It can be difficult to generate translated versions of images, and they may bloat the size of your app, slowing download speeds. Avoid text in images that needs to be translated, and avoid culture-specific images such as mailboxes, which are not common around the world. Avoid religious, political, or gender-specific images. The display of flesh, body parts, or hand gestures can also be a sensitive topic.
• Display numeric values, names, and addresses appropriately for global markets.
Dates, times, numbers, calendars, currency, telephone numbers, units of measurement, and paper sizes are all items that can be displayed differently based on culture. The order in which family and given names are displayed, and the format of addresses, can differ as well. Use standard date, time, and number displays. Use standard date and time picker controls. Use standard address information.
• Be aware when using color for meaning.
Be mindful when using color to convey meaning. Color choices may need to be reviewed by culture experts for customization. And always convey the same information by some means other than color, such as size, shape, or a label, for the benefit of colorblind readers.
Build date: 9/2/2013
Show:
© 2015 Microsoft | __label__pos | 0.849056 |
Class Diagram Relationships in UML with Examples
Many people consider class diagrams a bit more complicated to build compared with ER diagrams. While this might be true, this article helps clip some of the complexities of class diagrams in such a way that even non-programmers and less tech-savvy individuals will come to appreciate the usefulness of this modeling approach. In particular, this article explains how to correctly determine and implement the different class diagram relationships that are applicable in object-oriented modeling.
Class Diagram Relationships ( UML )
Relationships in UML class diagrams
Class Diagrams Explained
Class diagrams are visual representations of the static structure and composition of a particular system using the conventions set by the Unified Modeling Language (UML). Out of all the UML diagram types it is one of the most used ones. System designers use class diagrams as a way of simplifying how objects in a system interact with each other. Using class diagrams, it is easier to describe all the classes, packages, and interfaces that constitute a system and how these components are interrelated. For example, a simple class diagram may be used to show how an organization such as a convenient store chain is set up. On the other hand, precisely detailed class diagrams can readily be used as the primary reference for translating the designed system into a programming code.
The following figure is an example of a simple class diagram:
Simple Class diagram
Simple class diagram with attributes and operations
In the example, a class called “loan account” is depicted. Classes in class diagrams are represented by boxes that are partitioned into three:
1. The top partition contains the name of the class.
2. The middle part contains the class’s attributes.
3. The bottom partition shows the possible operations that are associated with the class.
Those should be pretty easy to see in the example: the class being described is a loan account, some of whose attributes include the type of loan, the name of the borrower/loaner, the specific date the loan was released and the loan amount. As in the real world, various transactions or operations may be implemented on existing loans such as renew and extend. The example shows how class diagrams can encapsulate all the relevant data in a particular scenario in a very systematic and clear way.
In object-oriented modeling, class diagrams are considered the key building blocks that enable information architects, designers, and developers to show a given system’s classes, their attributes, the functions or operations that are associated with them, and the relationships among the different classes that make up a system.
Relationships in Class Diagrams
Classes are interrelated to each other in specific ways. In particular, relationships in class diagrams include different types of logical connections. The following are such types of logical connections that are possible in UML:
Association
Association - One of the most common in class diagram relationships
Association
is a broad term that encompasses just about any logical connection or relationship between classes. For example, passenger and airline may be linked as above:
Directed Association
Directed Association Relationship in UML Class diagrams
Directed Association
refers to a directional relationship represented by a line with an arrowhead. The arrowhead depicts a container-contained directional flow.
Reflexive Association
Reflexive Association Relationship in UML Class diagrams
Reflexive Association
occurs when a class may have multiple functions or responsibilities. For example, a staff working in an airport may be a pilot, aviation engineer, a ticket dispatcher, a guard, or a maintenance crew member. If the maintenance crew member is managed by the aviation engineer there could be a managed by relationship in two instances of the same class.
Multiplicity
Multiplicity Relationship in UML Class diagrams
Multiplicity
is the active logical association when the cardinality of a class in relation to another is being depicted. For example, one fleet may include multiple airplanes, while one commercial airplane may contain zero to many passengers. The notation 0..* in the diagram means “zero to many”.
Aggregation
Aggregation Relationship
Aggregation
refers to the formation of a particular class as a result of one class being aggregated or built as a collection. For example, the class “library” is made up of one or more books, among other materials. In aggregation, the contained classes are not strongly dependent on the life cycle of the container. In the same example, books will remain so even when the library is dissolved. To render aggregation in a diagram, draw a line from the parent class to the child class with a diamond shape near the parent class.
Composition
Composition Relationship in Class Diagrams
Composition
is very similar to the aggregation relationship, with the only difference being its key purpose of emphasizing the dependence of the contained class to the life cycle of the container class. That is, the contained class will be obliterated when the container class is destroyed. For example, a shoulder bag’s side pocket will also cease to exist once the shoulder bag is destroyed. To depict a composition relationship in a UML diagram, use a directional line connecting the two classes, with a filled diamond shape adjacent to the container class and the directional arrow to the contained class.
Inheritance / Generalization
Inheritance Relationship in UML Class diagrams
Inheritance
refers to a type of relationship wherein one associated class is a child of another by virtue of assuming the same functionalities of the parent class. In other words, the child class is a specific type of the parent class. To depict inheritance in a UML diagram, a solid line from the child class to the parent class is drawn using an unfilled arrowhead.
Realization
Realization Relationship in UML Class diagrams
Realization
denotes the implementation of the functionality defined in one class by another class. To show the relationship in UML, a broken line with an unfilled solid arrowhead is drawn from the class that defines the functionality to the class that implements the function. In the example, the printing preferences that are set using the printer setup interface are being implemented by the printer.
Conclusion – Class diagram relationships are easy to understand
If you are a programmer or systems designer, you’ll be building or analyzing class diagrams quite often since they are, after all, the building blocks of object-oriented modeling. As demonstrated by this article, class diagram relationships are fairly easy to understand. As a rule of thumb, keeping class diagrams as simple as possible allows them to be more easily understood and appreciated by different types of audiences. For this purpose, remember to label your classes and relationships as descriptive as possible. Lastly, class diagrams also evolve as the real world systems they represent change. This implies that you don’t need to put in much detail in your first draft. All the classes, interfaces and relationships that are integral to the system or application you are designing will eventually emerge as the development process moves forward.
To make your job a lot easier, you can check out the online diagramming application offered on the Creately site. Besides being easy to use, the platform provides a comprehensive range of UML templates among other diagramming services. In addition, the platform supports collaboration and may be integrated into an existing company wiki or Intranet to keep diagrams well documented and updated. Having such a tool on your side will greatly improve your company’s development initiatives and will help your team meet its targets.
Now that you understand class diagram relationships it’s time to draw some, get started with this easy to use class diagram templates.
References:
1. UML basics: The class diagram An introduction to structure diagrams in UML 2 by Donald Bell
2. Class diagram as published on the Wikipedia website
3. The UML Class Diagram Part 1 as published in the website developer.com
4. The Class Diagram from Visual Case Tool – UML Tutorial as published on Visual Case website
5. Associations as published on the Sybase website
Tags :, , , , , ,
About the Author
About Nishadha
Software engineer turned tech evangelist. I handle marketing stuff here at Creately including writing blog posts and handling social media accounts. In my spare time I love to read and travel. Check out my personal blog Rumbling Lankan where I write about online marketing stuff.
26 thoughts on “Class Diagram Relationships in UML with Examples
1. aggregation an composition in a class diagramm are shown by the diamond on the aggregate calss side . It means the “Library” calss will have the diamond and not the “Books”. Very common mistake, most if the beginners make.
thanks noway
2. Hi noway,
You’re correct. We have corrected the mistake now. Thanks for taking the time to point that out.
3. Hi Nishi, its a great blog man. I just accidently came across this when browsing web.
Great work!! Keep it up.
4. Hi Nishada,your explanation is very clear to understand,can you send me the class modelling example of hospitality management system.
5. Your explanation of the reflexive association strikes me as odd.
Your explation of reflexive depicts an association class between ‘airport’ and ‘staff’ in which the association depicts the ‘multiple roles’ of the particular ‘staff’ in regard to the ‘airport’.
The reflexive association, to me, depicts the situation of a relation between equally typed instances, for example, like in a mesh network or in a (genealogical) parent – child construction of type Person.
Also consider adding the association class as a conceptual class relationship construct.
6. Hi Agecoat,
Thanks for visiting and leaving a comment. I think the example is valid but a better job could be done by adding an example. I have added an example to make it more clear.
7. Hi, I have a query. Can realization relationship exist between a Package and an Interface? Can we draw a realization relation (Empty head arrow) between a Package and an Interface in UML?
8. Out of curiosity, in the Airplane to Passengers Multiplicity example, shouldn’t this relationship be a Aggregation? In general, could you please give an example of when an association is more apt than an aggregation/composition with multiple objects?
9. The example you’ve given for inheritance/generalization should be the other way round. Bank Account should be the Parent. Fixed, Savings accounts should be the children. Bank account will hold the general attributes/ methods where as the Fixed account will have specific attributes/ methods inheriting the rest from the Bank account.
10. Large number of individuals looks for these details but they will not get effective one. I truly several thanks for discussing it
11. Good summary, just one thing, you have the wrong example in Composition. You should Library and Books again (as per Aggregation) and then talk about Shoulder Bag and Shoulder Bag Pocket in the text. Basically you need to relabel the diagram example. Cheers
12. on Directed association ,how does planer be the contained of passenger(container) I think it is wrong if not explain to me please!!!
13. Interesting the concept of aggregation and composition. Got few insights more to enrich my point of view frame.
Thanks fir sharing Nishadha, have a nice day.
Jim
14. in composition diagram above, do you think the books wouldn’t survive the library-death??. A more fitting example would be human and leg OR bulb and filament OR current and voltage, etc.
Leave a Reply
Your email address will not be published. Required fields are marked *
You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>
This blog uses premium CommentLuv which allows you to put your keywords with your name if you have had 9 approved comments. Use your real name and then @ your keywords (maximum of 3) | __label__pos | 0.914514 |
Keep a separate computer and Internet account for blackhat?
Discussion in 'Black Hat SEO' started by skypilot, Oct 22, 2009.
1. skypilot
skypilot Registered Member
Joined:
Jun 17, 2009
Messages:
63
Likes Received:
17
Is it advisable to keep a computer and Internet service (purchased with VCC) specifically for blackhat in case you could be traced by lawyers/cops to your IP?
Or is this parnoia?
2. Paper-Boy
Paper-Boy Elite Member
Joined:
Jun 17, 2009
Messages:
5,118
Likes Received:
1,826
buy a windows vps if you're that paranoid.
then connect through a proxy.
3. skypilot
skypilot Registered Member
Joined:
Jun 17, 2009
Messages:
63
Likes Received:
17
Wouldn't browsing/surfing/working through a proxy all the time be enough? How would the VPS protect identiy?
4. floppycode
floppycode Newbie
Joined:
Aug 29, 2009
Messages:
11
Likes Received:
0
if the proxy logs your data, than they can trace you. So if you are paranoid, you should buy an account for good proxy, or better VPS server.
5. Paper-Boy
Paper-Boy Elite Member
Joined:
Jun 17, 2009
Messages:
5,118
Likes Received:
1,826
buy a vps with a VCC. use fake info when it comes to registering/activating your VCC and same goes for your vps package.
once you get your vps setup, use a private proxy to do your BH stuff on your server.
obviously, this isn't foolproof but it's much better than using public stuff such as proxies and what not.
6. skypilot
skypilot Registered Member
Joined:
Jun 17, 2009
Messages:
63
Likes Received:
17
Wouldn't it be easiest to just use a VCC to buy a Clear wireless or AT&T wireless Internet account instead of using private proxies?
7. seosutra
seosutra Regular Member
Joined:
Oct 13, 2009
Messages:
211
Likes Received:
94
Occupation:
Variant
Location:
Outside the TCP I/Protocol ( Pun Intended)
How about VPN ??
| __label__pos | 0.998898 |
Sven Sven - 1 month ago 21
Linux Question
Start and stopping external program?
I want to start and stop an external program in Python3, on Linux.
This program is an executable, called
smip-tun,
located in the same folder as the source code and I'd like to be able to execute and control it from there with relative names.
Unfortunately, this does not work:
smip_tun = 0
def start_smip_tun(self):
smip_tun = subprocess.Popen(['smip-tun',DEFAULT_SERIAL_PORT])
def end_smip_tun(self):
smip_tun.terminate()
print("end")
But says it cannot find
smip-tun
. Efforts to specify the relative directory have failed. I was trying with
cwd
but cannot figure it out.
Any advice?
Edit:
Made Smip-tun global but the issue persists.
New code:
smip_tun = 0
def start_smip_tun(self):
global smip_tun
smip_tun = subprocess.Popen(['smip-tun',DEFAULT_SERIAL_PORT])
def end_smip_tun(self):
global smip_tun
smip_tun.terminate()
print("end")
Error message:
File "/home/sven/git/cerberos_manager/iot_network_api.py", line 40, in start_smip_tun
smip_tun = subprocess.Popen(['smip-tun',DEFAULT_SERIAL_PORT])
File "/usr/lib/python3.5/subprocess.py", line 947, in __init__
restore_signals, start_new_session)
File "/usr/lib/python3.5/subprocess.py", line 1551, in _execute_child
raise child_exception_type(errno_num, err_msg)
FileNotFoundError: [Errno 2] No such file or directory: 'smip-tun'
Answer
import os
os.chdir('.') # or change the . for the full path directory.
smip_tun = subprocess.Popen(['smip_tun',DEFAULT_SERIAL_PORT])
Also make sure your app do not have any extension(ex: smip-tun.py, smip-tun.sh...) | __label__pos | 0.529699 |
Andrew Mairose Andrew Mairose - 1 month ago 10x
Java Question
Get object with max frequency from Java 8 stream
I have an object with
city
and
zip
fields, let's call it
Record
.
public class Record() {
private String zip;
private String city;
//getters and setters
}
Now, I have a collection of these objects, and I group them by
zip
using the following code:
final Collection<Record> records; //populated collection of records
final Map<String, List<Record>> recordsByZip = records.stream()
.collect(Collectors.groupingBy(Record::getZip));
So, now I have a map where the key is the
zip
and the value is a list of
Record
objects with that
zip
.
What I want to get now is the most common
city
for each
zip
.
recordsByZip.forEach((zip, records) -> {
final String mostCommonCity = //get most common city for these records
});
I would like to do this with all stream operations. For example, I am able to get a map of the frequency for each
city
by doing this:
recordsByZip.forEach((zip, entries) -> {
final Map<String, Long> frequencyMap = entries.stream()
.map(GisSectorFileRecord::getCity)
.filter(StringUtils::isNotBlank)
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
});
But I would like to be able to do a single-line stream operation that will just return the most frequent
city
.
Are there any Java 8 stream gurus out there that can work some magic on this?
Here is an ideone sandbox if you'd like to play around with it.
Answer
You could have the following:
final Map<String, String> mostFrequentCities =
records.stream()
.collect(Collectors.groupingBy(
Record::getZip,
Collectors.collectingAndThen(
Collectors.groupingBy(Record::getCity, Collectors.counting()),
map -> map.entrySet().stream().max(Map.Entry.comparingByValue()).get().getKey()
)
));
This groups each records by their zip, and by their cities, counting the number of cities for each zip. Then, the map of the number of cities by zip is post-processed to keep only the city having the maximum count.
Comments | __label__pos | 0.50246 |
09 MySQL、Nginx
lix_uan
• 阅读 255
MySQL主从复制
准备工作
# 防火墙开放3306端口号
firewall-cmd --zone=public --add-port=3306/tcp --permanent
firewall-cmd --zone=public --list-ports
# 并将两台数据库服务器启动起来
systemctl start mysqld
主库配置
# 192.168.200.200
# /etc/my.cnf
log-bin=mysql-bin #[必须]启用二进制日志
server-id=200 #[必须]服务器唯一ID(唯一即可)
systemctl restart mysqld
# 创建数据同步的用户并授权
GRANT REPLICATION SLAVE ON *.* to 'xiaoming'@'%' identified by 'Root@123456';
# 登录Mysql数据库,查看master同步状态
show master status;
从库配置
# 192.168.200.201
# /etc/my.cnf
server-id=201 #[必须]服务器唯一ID
systemctl restart mysqld
# 登录Mysql数据库,设置主库地址及同步位置
change master to master_host='192.168.50.132',master_user='xiaoming',master_password='Root@123456',master_log_file='mysql-bin.000002',master_log_pos=154;
start slave;
# 查看从数据库的状态
show slave status\G;
踩坑
# 从机直接从主机克隆过来,UUID一致,导致主从复制失败
find -name auto.cnf
# 把server-UUID改成不一样的, 或直接删除这个文件
MySQL读写分离
<dependency>
<groupId>org.apache.shardingsphere</groupId>
<artifactId>sharding-jdbc-spring-boot-starter</artifactId>
<version>4.0.0-RC1</version>
</dependency>
create database rw default charset utf8mb4;
use rw;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(255) DEFAULT NULL,
`age` int(11) DEFAULT NULL,
`address` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
spring:
shardingsphere:
datasource:
names:
master,slave
# 主数据源
master:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.200.200:3306/rw?characterEncoding=utf-8
username: root
password: root
# 从数据源
slave:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.200.201:3306/rw?characterEncoding=utf-8
username: root
password: root
masterslave:
# 读写分离配置
load-balance-algorithm-type: round_robin #轮询
# 最终的数据源名称
name: dataSource
# 主库数据源名称
master-data-source-name: master
# 从库数据源名称列表,多个逗号分隔
slave-data-source-names: slave
props:
sql:
show: true #开启SQL显示,默认false
main:
allow-bean-definition-overriding: true
Nginx下载安装
yum -y install gcc pcre-devel zlib-devel openssl openssl-devel wget
wget https://nginx.org/download/nginx-1.16.1.tar.gz
tar -zxvf nginx-1.16.1.tar.gz
# 配置Nginx编译环境, --prefix 指定的目录,就是我们安装Nginx的目录
cd nginx-1.16.1
./configure --prefix=/usr/local/nginx
# 编译&安装
make & make install
Nginx常用命令
cd /sbin
# 查看版本
./nginx -v
# 检查配置文件
./nginx -t
# 启动
./nginx
# 访问80端口
systemctl stop firewalld
firewall-cmd --zone=public --add-port=80/tcp --permanent
firewall-cmd --reload
# 停止
./nginx -s stop
# 修改配置文件后需要重新加载
./nginx -s reload
# /etc/profile配置环境变量
# 踩坑
# Nginx 访问页面403
vi /etc/selinux/config
SELINUX=disabled
vi nginx.conf
user root;
nginx -s reload
Nginx应用
部署静态资源
# conf/nginx.conf
server {
listen 80; #监听端口
server_name localhost; #服务器名称
location / { #匹配客户端请求url
root html; #指定静态资源根目录
index index.html; #指定默认首页
}
}
反向代理
server {
listen 82;
server_name localhost;
location / {
proxy_pass http://192.168.200.201:8080; #反向代理配置,将请求转发到指定服务
}
}
负载均衡
#upstream指令可以定义一组服务器, weight配置权重
upstream targetserver{
server 192.168.200.201:8080 weight=10;
server 192.168.200.201:8081 weight=5;
}
server {
listen 8080;
server_name localhost;
location / {
proxy_pass http://targetserver;
}
}
点赞
收藏
评论区
推荐文章
暂无数据
lix_uan
lix_uan
Lv1
学无止境,即刻前行
文章
7
粉丝
5
获赞
0 | __label__pos | 0.72021 |
Strict Mode(嚴格模式)
Javascript中的物件導向
對於一個直譯式語言而言,物件導向特性是不是有那麼樣的重要,有很多不同的意見,有人認為物件導向除了會拖慢執行的速度,不良的物件導向語法,反而會出現更多不預期的程式臭蟲(bugs)。
Javascript中的物件導向存在有很多與現在流行語言完全不同的物件導向特性,也就是說如果你有學過Java、C++之類的物件導向語法,在Javascript中不是很難作到,就是要用很有技巧性的方式才能達成(trick),尤其是在舊的Javascript標準中,如果不依靠這些技巧,有些物件導向的特性根本很難作得到。當然,新的Javascript標準(ECMAScript5或更新的6)中,對於OOP已經有大幅度的改進。
網路上有關於Javascript的物件導向開發部份的教學,很多都是舊式的標準的內容,新的標準中已經有很多新的作法,相較於舊式的內容,使用上更為簡單而且安全。例如用於建立物件的Object.create方法,用於getter與getter的方法,以及許多方便開發者的Array方法。
本文專注於相容於目前大部份瀏覽器(與Node.js)的物件導向新特性,相容性可以到ECMAScript相容表觀看。
Strict Mode(嚴格模式)
Strict Mode是ECMAScript 5中的新功能之一,不過目前在瀏覽器端的開發並不建議使用(例如IE9就不支援),原因是大部份瀏覽器都只有部份支援而已,如果在不支援的瀏覽器上使用,也沒有效果(跳過)。在Node.js開發時則是建議使用,在每個程式檔案前頭加上:
"use strict";
var v = "after that, we are all strict mode script!";
也可以在某個函式中使用,不過只會在上下文中被限制為嚴格模式:
function imStrict(){
"use strict";
// ... after that, we are all strict mode script!
}
或是限定在某個函式庫(or外掛)中使用,不會影響到外面的程式碼:
// Non-strict code...
(function(){
"use strict";
// Define your library strictly...
})();
// Non-strict code...
經過Strict Mode宣告後,有部份的語法是會"嚴格"規定無法使用,這些語法通常是原本在Javascript中的小錯誤(Mistakes),現在則會變成中斷或無法執行的錯誤(Error)。
變數(Variable)與屬性(Property)
沒有經過宣告的變數與屬性會直接造成錯誤,如果沒有使用Strict前,則是會變成一個全域(global)物件的屬性:
"use strict"
a = 12;
變數要加上var宣告
delete運算子
delete運算子用在刪除變數或屬性、或陣列中的元素。用了Strict模式後,如果試圖要刪除不是可設定的(Configurable)物件屬性,也就是試圖刪除變數、函式、傳入值…等等,就會產生中斷執行的錯誤:
var foo = "test";
function test(){}
delete foo; // Error
delete test; // Error
function test2(arg) {
delete arg; // Error
}
只有在刪除物件中的可設定的(Configurable)物件屬性才能使用:
window.b = 34;
delete window.b;
少用delete運算子,要使用時要注意能使用的場合只有一個情況
重覆性不允許
屬性名稱宣告
var myObject = {foo:1, bar:2, foo:1}; //throws an exception.
參數名稱
function print(value, value) {} //throws exception.
getter或setter
// SyntaxError
var foo = {
get x() {},
get x() {}
};
// the same with setters
// SyntaxError
var bar = {
set y(value) {},
set y(value) {}
};
不要使用重覆的變數或函式名稱
8進位(Octal)數用與跳脫(escape characters)宣告均不允許
這個宣告會不被允許主要原因是在Javascript中使用parseInt時會混亂。
var testStrict = 010; // throws exception
var testStrict = \010; // throws exception.
8進位可以用字串先宣告,處理上要注意。
“eval”與“arguments”不能作為變數、參數、函式、物件名稱
// All generate errors...
obj.eval = ...
obj.foo = eval;
var eval = ...;
for ( var eval in ... ) {}
function eval(){}
function test(eval){}
function(eval){}
new Function("eval")
用在物件內的屬性名稱倒是可以:
"use strict";
// OK
var foo = {
eval: 10,
arguments: 20
};
// OK
foo.eval = 10;
foo.arguments = 20;
eval也會變成沙盒環境(sandbox environment),意思是執行完就會把其中的變數或方法移除回收掉:
"use strict";
eval("var x = 10; alert(x);"); // 10
alert(x); // "x" is not defined
要破除這個規則可以使用indirect eval:
"use strict";
("indirect", eval)("var x = 10; alert(x);"); // 10
alert(x); // 10
eval的確少用為妙。不需要用保留字當變數或函式名稱。
未來保留字
這些未來Javascript可能使用到的保留字都不能使用在變數、方法名稱上:
1. implements
2. interface
3. let
4. package
5. private
6. protected
7. public
8. static
9. yield
“this”關鍵字
this不是自動成為物件,而是預設變成undefined(或null)。這個undefined可以避免在使用constructors時忘了使用new關鍵字。
"use strict";
function A(x) {
this.x = x;
}
// forget "new" keyword,
// error, because undefined.x = 10
var a = A(10);
var b = new A(10); // OK
this不要用在不是物件導向語法的全域方法中,會回傳undefined
with敘述不允許
with整個不能使用,這是有考量會混亂使用的情況。
Strict Mode優點
• 協助程式碼中常見小問題(Mistakes)或不良語法(bad syntax)成為實際的中斷執行錯誤
• 開發者可以更容易發覺到不安全的語法或一些物件導向設計程式碼的問題
• 它關閉了某些容易造成混淆或誤用的語法或運算子
參考資料 | __label__pos | 0.682606 |
Functional analysis is the study of infinite-dimensional vector spaces, often with additional structures (inner product, norm, topology), with typical examples given by function spaces. The subject also includes the study of linear and non-linear operators on these spaces, as well as measure, ...
learn more… | top users | synonyms (1)
4
votes
2answers
33 views
If $\lim_{x\to\infty} [f(x+1)-f(x)] =l$ then $\lim_{ x\to\infty}f(x)/x =l$ ($f$ is continuous)
Prove that if $f$ is continuous on $\mathbb R$ and $$\lim_{x \to +\infty} [f(x+1)-f(x)] = l,$$ then $$\lim_{x\to +\infty} f(x)/x =l.$$ So I've been trying for hours to use the series ...
1
vote
0answers
13 views
Bounded Measurable Functions: Pointwise Limit vs. Uniform Limit
Agreement All notions are up to null sets. Limits are meant by simple functions. Problem Given a finite measure space $\mu(\Omega)<\infty$ and a Banach space $E$. Consider bounded measurable ...
0
votes
1answer
6 views
Generalized Riemann Integral: Uniform Convergence
Disclaimer This thread is meant to record. See: Answer own Question And it is written as question. Have fun! :) Reference This thread is related to: Generalized Riemann Integral: Nonexample? ...
0
votes
0answers
10 views
Projections as a dense subset of $\ell_p^*$
I'm trying to prove that weak convergence in $ \ell_p^*$ is equivalent to coordinatewise convergence and boundedness, i.e. $$ a_n^{(k)} \text{ converges weakly to}~ a_0^{(k)} \iff \exists_{ M>0} ...
0
votes
1answer
8 views
Equivalence of dual spaces of Sobolev Spaces
I have a quick question: Is the following equivalence true for Sobolev Spaces $(W^{1,p}(\Omega))^{*} = W^{-1,p}(\Omega) = (W^{1,p}_{0}(\Omega))^{*}$ where $W^{1,p}_{0}(\Omega)$ is the closure of ...
1
vote
1answer
8 views
norm of bounded linear operator restricted to dense subspace
I have no idea how to do this question I was given in class. Let $E$ and $F$ be normed spaces and let $T \in \mathcal{L}(E,F)$. Suppose that $E_0 \subseteq E$ is a dense subspace. Show that ...
1
vote
0answers
11 views
Under what conditions, depending on my particular choice of $f$ and $g$ (other than $f\in L^1$ and $g\in L^\infty$) under which $f\cdot g$ is in L^1?
Is there a possibility of a function $f\in L^{1}(\Omega)$ and $g \in L^{2}(\Omega)$ implying that $f\cdot g\in L^{1}(\Omega)$? At least can you let me know what suitable function space $g$ is in some ...
0
votes
1answer
28 views
A Challenge on linear functional and bounding property
I took a midterm exam and after that wrote this problem down. My instructor was unable to solve it. The problem is copied here in order for anyone to help me. Suppose $f:E\to \mathbb{C}$ is a ...
0
votes
1answer
12 views
Uniform Boundedness Principle
This is a homework question, I have no clue where to start! Use Uniform Boundedness Principle to prove the following statement. A subset $X$ of a normed space $E$ is bounded if and only if $f(X)$ is ...
0
votes
0answers
20 views
Unital maps taking values in abelian C*-algebras
It is known that a bounded linear functional $f$ on a unital C*-algebra $A$ is positive if and only if $f(I)\geqslant 0$. Is the same true for bounded linear operators $T\colon A\to C(X)$ with $T(I) = ...
2
votes
3answers
52 views
An example of a function in $L^1[0,1]$ which is not in $L^p[0,1]$ for any $p>1$
Title says most of it. Could you help me find an example? It is easy obviously to show a function that would not be in $L^p[0,1]$ for a specific $p$ (say $(1/x)^{1/p}$, but I can't see how it would ...
0
votes
1answer
18 views
Showing self adjointness
$\pi:$ $Lx=\sum_{j=0}^{n}(p_{n-j}x^{(j)})^{(j)}$,$\,\,$ $x^{(j)}(a)=x^{(j)}(b)=0,\, j=0,1,...,n-1.$ where $p_{n-j}\in C^{n-j}[a,b]$ are real and $p_0(t)\neq0$ on $[a,b]$. I want to show that the ...
1
vote
0answers
17 views
Prove domain of Dependence Inequality for the Wave Equation?
Let $(x_0,t_0)\in R^{n+1}$ with $t_0>0$, and let $\Omega$ be the conical domain in $R^{n+1}$ bounded by the backward characteristic cone with apex at $(x_0,t_0)$ and by the plane $t=0$. Suppose ...
0
votes
1answer
22 views
If $f \in L^{1}(\Omega)$, $g \in L^{2}(\Omega)$, with $\Omega$ a bounded domain in $\mathbb{R}^n$, then can $f.g$ be in $L^1{\Omega}$?.
I have come up with an argument which is as follows. Please correct me if it makes no sense. Consider $\int_{\Omega}|f.g|dm$. Then if $|f|\in L^1$ then $\sqrt{|f|}\in L^2$. Hence we have ...
1
vote
2answers
26 views
Stone's Theorem and Functional Calculus
I've asked a few questions on here before regarding functional calculus but I am still having a bit of trouble. I have been reading up on Stone's theorem for unitary groups, and going through the ...
2
votes
1answer
30 views
Reproducing kernel Hilbert space, why?
Let $K: X \times X \rightarrow \mathbb{C}$ be a positive definite kernel on a set $X$, i.e. for any $x_1, \cdots, x_n \in X$, the matrix $$ [K(x_i, x_j)]_{ij} \in \mathbb{C}^{n \times n} $$ is ...
0
votes
1answer
16 views
How do I construct a Schauder basis of $l^2$ with the set $\{v_n\}
How do I construct a Schauder basis of $l^2$ with the set $\{v_n\} \subset l^2$, where $v_n=\frac{1}{\sqrt{2}}(e_n-e_{n+1})$ if $n$ is odd and $v_n=\frac{1}{\sqrt{2}}(e_n+e_{n-1})$ if $n$ even. Note ...
0
votes
0answers
11 views
$L^p$ is a quasi normed space for $0<p<1$ [duplicate]
I know that $L^p$ is a vector space for $p>0$ and a normed space for $p \geqslant 1$ now I need show that for $ 0<p<1$ and $f,g \in L^p$ exist $K \in \mathbb{R}$ such that $||f+g||_p ...
0
votes
0answers
18 views
Choosing a clever “test function” in Sobolev spaces.
Given $\mathbf{f}$ with $f_1,...,f_N\in L^2(\Omega)$ $$\int_\Omega \mathbf{f} \cdot \nabla v = 0 \quad\forall v \in H_0^1(\Omega)$$ we have $\mathbf{f} = \mathbf{0}$ a.e. since $\mathbf{f} \in ...
1
vote
0answers
10 views
Wiener's lemma and Hulanicki's lemma
Let $\mathcal{A}(\mathbf{T})$ be the Banach algebra of continuous complex-valued functions on the unit circle with absolutely convergent Fourier series. Then Wiener's lemma states that if $f \in ...
1
vote
0answers
17 views
Weak convergence in $l^p$-space [on hold]
Let $1<p<\infty$, $x_n=(x_n^{(j)})_j\in l^p$ for $n\in \mathbb N$ and $x=(x^{(j)})_j\in l^p$. Show that $$x_n\rightharpoonup x\iff \forall j\in \mathbb N:x_n^{(j)}\rightarrow x^{(j)}, ...
1
vote
0answers
17 views
Weak convergence in Hilbert space implies strong convergence of averages for some subsequence
Let $H$ Hilbert Space. Show that if $x_n\rightharpoonup x$ then there exists a subsequence $\{x_{nk}\}$ of $\{x_{n}\}$ such that the sequence $\lim_{m\rightarrow \infty } ...
0
votes
1answer
22 views
an additive bijective map
Let H be a Hilbert space and $\Phi:B(H)\longrightarrow B(H)$ is an additive bijective map. If $\mathbb{R}I⊆\Phi(\mathbb{R}I)$, can we conclude by the bijectivity of $\Phi$ that ? ...
1
vote
1answer
31 views
Projection of $H^1([0,1])$ on its subspace .
Let $H^1([0,1])$ be the Sobolev space $W^{1,2}([0,1])$ with the scalar product $\langle f,g\rangle = \int_0^1 fg + \int_0^1 f'g'$. We can consider the closed and convex subset $K=\{f \in H^1([0,1] ...
3
votes
1answer
26 views
Graph of weakly continuous linear operator
I have a few questions regarding the graph of an operator. Consider the operator $T:X \rightarrow Y$ between Banach spaces $X,Y$. Assume that $T$ is a linear operator which is (weak, weak)-continuous, ...
6
votes
2answers
45 views
$\int_{-1}^{1}|f(t)|dt \geq C\left(\int_{0}^{2}|f(t)|^2\right)^{1/2}$ for polynomials
Prove that there exists constant $C>0$ that for all $f \in P_n$ we have: $$\int_{-1}^{1}|f(t)|dt \geq C\left(\int_{0}^{2}|f(t)|^2\right)^{1/2}$$ Where $P_n$ is space of polynomials with ...
0
votes
1answer
21 views
Find eigenspectrum of $T^{*}$
Let {$u_n$} be an orthonormal basis of Hilbert space $H$. Let $T \in B(H)$ s.t. $T(u_n)=u_{n+1}$ for $n \ge 1$. Find eigenspectrum of $T^{*}$. I have tried to find it taking the corresponding matrix ...
1
vote
1answer
47 views
Hermite functions as eigenvectors of Fourier transform
In order to find an orthogonal basis of eigenvectors of the Fourier transform operator $F:L_2(\mathbb{R})\to L_2(\mathbb{R})$, $f\mapsto\lim_{N\to\infty}\int_{[-N,N]}f(x)e^{-i\lambda x}d\mu_x$ for ...
0
votes
1answer
16 views
Show $\sigma(T)=\sigma{(\overline{T^{*}})}$
Let $T \in B(H)$ be a bounded operator. Is $\sigma(T)=\sigma{(\overline{T^{*}})}$ true for $T$? $\textbf{TRY-}$ I have proved it is true for normal operator but could not do it for bounded ...
1
vote
0answers
27 views
Show that both $S$ and $T$ are bounded. [duplicate]
Let $S$ and $T$ be linear map defined on hilbert space $H$ s.t. $\langle Su,v \rangle=\langle u,Tv\rangle $ $\forall u,v \in H$. Then show that both $S$ and $T$ are bounded. $\textbf{TRY-}$ If I can ...
1
vote
0answers
14 views
When is a metrizable topological vector space locally bounded?
Consider a topological vector space $E$ with topology $\sigma$. Suppose that $E$ is metrizable, in other words, that there exists a metric $d$ on $E$ that induces the topology $\sigma$. One can then ...
0
votes
1answer
16 views
find a sequence converging to zero but not the elemet of lp space for every 1<_p<infinity
I am studying functional analysis and I have a problem about finding a sequence converging to zero such that this sequence is not in lp for every p. By lp I mean lp={(x_k)=(x1,x2,...):Σ|x_k|^p_2 it is ...
0
votes
3answers
23 views
When talking about a normed vector space, does it's metric always need to be the induced one?
The title basically says it all. If we have a normed vector space, is it possible to work with the space as a metric space with a different metric than the induced one? So if the space is $(X,||\ ...
0
votes
0answers
24 views
The space of distribution $H^{-1}$
Let's suppose to have a function $u$ in the space $L^\infty(0,T;H^1(\mathbb{R}^n))$ with $\partial_t u\in L^\infty(0,T;H^{-1}(\mathbb{R}^n))$. So $\partial_t u$ is a linear and continuous functional ...
1
vote
1answer
12 views
Positive invertable element of a C*- algebra
The following is Theorem 2.2.5 of Murphy's C*-algebras and operator theory: Let $A$ be an unital C*-algebra and $a,b$ are positive invertable elements, if $a\leq b$, then $0\leq b^{-1}\leq a^{-1}$. ...
0
votes
1answer
11 views
A minimisation problem in an Hausdorff space
Let X an hausdorff space, K a compact set, f a lower continuous function. How can you prove that f has a minimum on K? Ps: be careful X is not specially a metric space
2
votes
1answer
29 views
As $\lambda \to \infty$, $||R_{\lambda}(T)|| \to 0$
"Let $T \in B(X,X)$. Prove that $||R_{\lambda}(T)|| \to 0$ as $\lambda \to \infty$." We have that $R_{\lambda}(T)x=(T-\lambda I)^{-1}(x)$. The problem doesn't specify but the book says that they will ...
0
votes
0answers
23 views
Banach Spaces: Improper Riemann Integral
Disclaimer This thread is related to: Stone's Theorem Definition Given a measure space $\Omega$ and a Banach space $E$. Consider functions $F:\Omega\to E$. Denote the measurable subsets of finite ...
5
votes
1answer
46 views
Theorem 3.54 (about certain rearrangements of a conditionally convergent series) in Baby Rudin: A couple of questions about the proof
Here's the statement of Theorem 3.54 in Principles of Mathematical Analysis by Walter Rudin, 3rd edition: Let $\sum a_n$ be a series of real numbers which converges, but not absolutely. Suppose ...
0
votes
1answer
14 views
Topology induced by semi-norm and P-topology
Let V be an abstract vector space over F and P a family of semi-norms on V. We can define a topology on V by declaring its base to consist of subsets of V of the form {v∈V | p1(v−x)<ϵ ∧ … ∧ ...
0
votes
1answer
29 views
Proving dense set is core for a self adjoint operator
Let $A$ be a self adjoint operator in a Hilbert space $H$ and $D\subseteq D(A)$ a dense subset such that $$ e^{iAt}:D \to D. $$ How can I show that $D$ is a core for $A$? I need to show that ...
-1
votes
0answers
25 views
a problem about the application of Banach-Steinhaus theorem [on hold]
Let $\{x_k\}$ to be a sequence in Banach space $X$. Prove that if for any f in $X^*$, $\sum_{k=1}^\infty |f(x_k)|<+\infty$, then there exist a constant M s.t. for every $f\in X^*$ we have ...
1
vote
0answers
15 views
Green-Operator for Sturm-Liouville Differential equation compact on Sobolev space?
Let $g$ be Green's Function for a Sturm-Liouville differential equation. Is the operator $G: H_{0}^{1}(0,1) \rightarrow H_{0}^{1}(0,1)$ defined by $(Gf)(x) := \int_{0}^{1} g(x,y)f(y) dy, \quad f \in ...
1
vote
1answer
51 views
Recapitulated: Stone's Theorem Integral
This problem grew out from: Stone's Theorem Integral For a definition, a nonexample and a comparison see: Generalized Riemann Integral: Definition Generalized Riemann Integral: Nonexample ...
1
vote
1answer
25 views
Approximation of $f \in L^1_{loc}$
I am trying to prove the following statement: If $\Omega$ open in $\mathbb{R}^n$, $f \in L^1_{loc}(\Omega)$ (a set of all functions whose integrals on compact sets exist) and $\int_{\Omega}f\cdot g ...
0
votes
0answers
9 views
Visual notion of tangential gradient
Before I begin, this question is related to personal reading and is not in any way connected to an assessment/assignment. I am struggling to visualise the tangential gradient. As I understand it, the ...
0
votes
1answer
21 views
Find a tight frame of exponentials for $L^2(T)$, where $T \subset \mathbb{R}^2$ is a triangle with vertices $(0,1)$, $(1,0)$, and $(-1,0)$.
Find a tight frame of exponentials for $L^2(T)$, where $T \subset \mathbb{R}^2$ is a triangle with vertices $(0,1)$, $(1,0)$, and $(-1,0)$. Normally, I would do is find a matrix representation and ...
2
votes
1answer
36 views
Verify that the set $\{ (b-a)^{-\frac{1}{2}}e^\frac{2\pi ixj}{b-a} \}$ is an orthonormal basis of $L^2(a,b)$.
Let $H=L^2(a,b)$ with $a<b$. Verify that the set $\{ (b-a)^{-\frac{1}{2}}e^\frac{2\pi ixj}{b-a} \}$ is an orthonormal basis of $L^2(a,b)$. Verify also that $$\{(b_1-a_1)^{-\frac{1}{2}} \cdot \dots ...
0
votes
2answers
23 views
Norm of orthogonal projection operator $P$, if $\text{Im}\,P\subseteq\text{Im}\,Q$, with $Q$ also an orthogonal projection
In Rynne & Youngson: Linear Functional Analysis, there is an exercise stated as Let $\mathcal{H}$ be a complex Hilbert space and let $P$, $Q\in B(\mathcal{H})$ be orthogonal projections. Show ...
-1
votes
0answers
24 views
$[f=q]$ is closed implies $f$ is continuous. [on hold]
Define $H=[f=q]$ to be the set of points such that $f(x)=q$. Let us assume that H is closed. Then the complement of H is open and nonempty (since $f$ does not vanish identically - ""i don't understand ... | __label__pos | 0.927193 |
/************************************************************************************************/ /* Stata User File for H42 Data */ /* */ /* This file contains information and a sample Stata program to create a permanent */ /* Stata dataset for users who want to use Stata in processing the MEPS data provided */ /* in this PUF release. Stata (StataCorp) has the capability to produce */ /* appropriate standard errors for estimates from a survey with a complex sample */ /* design such as the Medical Expenditure Panel Survey (MEPS). */ /* The input file for creating a permanent Stata dataset is the ASCII data file */ /* (H42.DAT) supplied in this PUF release, which in turn can be extracted from the */ /* .EXE file. After entering the Stata interactive environment access the Stata DO-File */ /* editor by clicking on the appropriate icon in the command line at the top of the */ /* screen. Copy and paste the following Stata commands into the editor and save as a */ /* DO file. A DO file is a Stata program which may then be executed using the DO command. */ /* For example, if the DO file is named H42.DO and is located in the directory */ /* C:\MEPS\PROG, then the file may be executed by typing the following command into */ /* the Stata command line: */ /* do C:\MEPS\PROG\H42.DO */ /* The program below will output the Stata dataset H42.DTA */ /************************************************************************************************/ #delimit ; cd C:\MEPS\DATA; log using H42F2.log, replace; clear; * INPUT ALL VARIABLES; infix long DUID 1-5 int PID 6-8 str DUPERSID 9-16 str EVNTIDX 17-28 byte SEETLKPV 29-30 using H42F2.dat; *DEFINE VARIABLE LABELS; label variable DUID "DWELLING UNIT ID"; label variable PID "PERSON NUMBER"; label variable DUPERSID "PERSON ID (DUID + PID)"; label variable EVNTIDX "EVENT ID (DUPERSID + EVENTN)"; label variable SEETLKPV "DID P VISIT PROV IN PERSON OR TELEPHONE"; *DEFINE VALUE LABELS FOR REPORTS; label define H42F20001X -1 "-1 INAPPLICABLE" -2 "-2 DETERMINED IN PREVIOUS ROUND" -3 "-3 NO DATA IN ROUND" -7 "-7 REFUSED" -8 "-8 DK" -9 "-9 NOT ASCERTAINED" 1 "1 SAW PROVIDER" 2 "2 TELEPHONE CALL" ; * ASSOCIATE VARIABLES WITH VALUE LABEL DEFINITIONS; label value SEETLKPV H42F20001X; *DISPLAY A DESCRIPTION OF STATA FILE; describe; *LIST FIRST 20 OBSERVATIONS IN THE FILE; list in 1/20; save H42F2, replace; #delimit cr * data file is stored in H42F2.dta * log file is stored in H42F2.log log close /************************************************************************************************ NOTES: 1. This program has been tested on Stata Version 10 (for Windows). 2. This program will create a permanent Stata dataset. All additional analyses can be run using this dataset. In addition to the dataset, this program creates a log file named H42.LOG and a data file named H42.DTA. If these files (H42.DTA and H42.LOG) already exist in the working directory, they will be replaced when this program is executed. 3. If the program ends prematurely, the log file will remain open. Before running this program again, the user should enter the following Stata command: log close 4. The cd command assigns C:\MEPS\DATA as the working directory and location of the input ASCII and output .DTA and .LOG files and can be modified by the user as necessary. 5. Stata commands end with a carriage return by default. The command #delimit ; temporarily changes the command ending delimiter from a carriage return to a semicolon. 6. The infix command assumes that the input variables are numeric unless the variable name is prefaced by str. For example, DUPERSID is the a string (or character) variable. ************************************************************************************************/ | __label__pos | 0.606609 |
Class Ember.Application
public
An instance of Ember.Application is the starting point for every Ember application. It helps to instantiate, initialize and coordinate the many objects that make up your app.
Each Ember app has one and only one Ember.Application object. In fact, the very first thing you should do in your application is create the instance:
1
window.App = Ember.Application.create();
Typically, the application object is the only global variable. All other classes in your app should be properties on the Ember.Application instance, which highlights its first role: a global namespace.
For example, if you define a view class, it might look like this:
1
App.MyView = Ember.View.extend();
By default, calling Ember.Application.create() will automatically initialize your application by calling the Ember.Application.initialize() method. If you need to delay initialization, you can call your app's deferReadiness() method. When you are ready for your app to be initialized, call its advanceReadiness() method.
You can define a ready method on the Ember.Application instance, which will be run by Ember when the application is initialized.
Because Ember.Application inherits from Ember.Namespace, any classes you create will have useful string representations when calling toString(). See the Ember.Namespace documentation for more information.
While you can think of your Ember.Application as a container that holds the other classes in your application, there are several other responsibilities going on under-the-hood that you may want to understand.
Event Delegation
Ember uses a technique called event delegation. This allows the framework to set up a global, shared event listener instead of requiring each view to do it manually. For example, instead of each view registering its own mousedown listener on its associated element, Ember sets up a mousedown listener on the body.
If a mousedown event occurs, Ember will look at the target of the event and start walking up the DOM node tree, finding corresponding views and invoking their mouseDown method as it goes.
Ember.Application has a number of default events that it listens for, as well as a mapping from lowercase events to camel-cased view method names. For example, the keypress event causes the keyPress method on the view to be called, the dblclick event causes doubleClick to be called, and so on.
If there is a bubbling browser event that Ember does not listen for by default, you can specify custom events and their corresponding view method names by setting the application's customEvents property:
1
2
3
4
5
6
let App = Ember.Application.create({
customEvents: {
// add support for the paste event
paste: 'paste'
}
});
To prevent Ember from setting up a listener for a default event, specify the event name with a null value in the customEvents property:
1
2
3
4
5
6
7
let App = Ember.Application.create({
customEvents: {
// prevent listeners for mouseenter/mouseleave events
mouseenter: null,
mouseleave: null
}
});
By default, the application sets up these event listeners on the document body. However, in cases where you are embedding an Ember application inside an existing page, you may want it to set up the listeners on an element inside the body.
For example, if only events inside a DOM element with the ID of ember-app should be delegated, set your application's rootElement property:
1
2
3
let App = Ember.Application.create({
rootElement: '#ember-app'
});
The rootElement can be either a DOM element or a jQuery-compatible selector string. Note that views appended to the DOM outside the root element will not receive events. If you specify a custom root element, make sure you only append views inside it!
To learn more about the events Ember components use, see components/handling-events.
Initializers
Libraries on top of Ember can add initializers, like so:
1
2
3
4
5
6
7
Ember.Application.initializer({
name: 'api-adapter',
initialize: function(application) {
application.register('api-adapter:main', ApiAdapter);
}
});
Initializers provide an opportunity to access the internal registry, which organizes the different components of an Ember application. Additionally they provide a chance to access the instantiated application. Beyond being used for libraries, initializers are also a great way to organize dependency injection or setup in your own application.
Routing
In addition to creating your application's router, Ember.Application is also responsible for telling the router when to start routing. Transitions between routes can be logged with the LOG_TRANSITIONS flag, and more detailed intra-transition logging can be logged with the LOG_TRANSITIONS_INTERNAL flag:
1
2
3
4
let App = Ember.Application.create({
LOG_TRANSITIONS: true, // basic logging of successful transitions
LOG_TRANSITIONS_INTERNAL: true // detailed logging of all routing steps
});
By default, the router will begin trying to translate the current URL into application state once the browser emits the DOMContentReady event. If you need to defer routing, you can call the application's deferReadiness() method. Once routing can begin, call the advanceReadiness() method.
If there is any setup required before routing begins, you can implement a ready() method on your app that will be invoked immediately before routing begins.
Show:
Module: ember
Defines the properties that will be concatenated from the superclass (instead of overridden).
By default, when you extend an Ember class a property defined in the subclass overrides a property with the same name that is defined in the superclass. However, there are some cases where it is preferable to build up a property's value by combining the superclass' property value with the subclass' value. An example of this in use within Ember is the classNames property of Ember.View.
Here is some sample code showing the difference between a concatenated property and a normal one:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
const Bar = Ember.Object.extend({
// Configure which properties to concatenate
concatenatedProperties: ['concatenatedProperty'],
someNonConcatenatedProperty: ['bar'],
concatenatedProperty: ['bar']
});
const FooBar = Bar.extend({
someNonConcatenatedProperty: ['foo'],
concatenatedProperty: ['foo']
});
let fooBar = FooBar.create();
fooBar.get('someNonConcatenatedProperty'); // ['foo']
fooBar.get('concatenatedProperty'); // ['bar', 'foo']
This behavior extends to object creation as well. Continuing the above example:
1
2
3
4
5
6
let fooBar = FooBar.create({
someNonConcatenatedProperty: ['baz'],
concatenatedProperty: ['baz']
})
fooBar.get('someNonConcatenatedProperty'); // ['baz']
fooBar.get('concatenatedProperty'); // ['bar', 'foo', 'baz']
Adding a single property that is not an array will just add it in the array:
1
2
3
4
let fooBar = FooBar.create({
concatenatedProperty: 'baz'
})
view.get('concatenatedProperty'); // ['bar', 'foo', 'baz']
Using the concatenatedProperties property, we can tell Ember to mix the content of the properties.
In Ember.Component the classNames, classNameBindings and attributeBindings properties are concatenated.
This feature is available for you to use throughout the Ember object model, although typical app developers are likely to use it infrequently. Since it changes expectations about behavior of properties, you should properly document its usage in each individual concatenated property (to not mislead your users to think they can override the property in a subclass).
Module: ember
The DOM events for which the event dispatcher should listen.
By default, the application's Ember.EventDispatcher listens for a set of standard DOM events, such as mousedown and keyup, and delegates them to your application's Ember.View instances.
If you would like additional bubbling events to be delegated to your views, set your Ember.Application's customEvents property to a hash containing the DOM event name as the key and the corresponding view method name as the value. Setting an event to a value of null will prevent a default event listener from being added for that event.
To add new events to be listened to:
1
2
3
4
5
6
let App = Ember.Application.create({
customEvents: {
// add support for the paste event
paste: 'paste'
}
});
To prevent default events from being listened to:
1
2
3
4
5
6
7
let App = Ember.Application.create({
customEvents: {
// remove support for mouseenter / mouseleave events
mouseenter: null,
mouseleave: null
}
});
Module: ember
The Ember.EventDispatcher responsible for delegating events to this application's views.
The event dispatcher is created by the application at initialization time and sets up event listeners on the DOM element described by the application's rootElement property.
See the documentation for Ember.EventDispatcher for more information.
Module: ember
Destroyed object property flag.
if this property is true the observers and bindings were already removed by the effect of calling the destroy() method.
Module: ember
Destruction scheduled flag. The destroy() method has been called.
The object stays intact until the end of the run loop at which point the isDestroyed flag is set.
Module: ember
Defines the properties that will be merged from the superclass (instead of overridden).
By default, when you extend an Ember class a property defined in the subclass overrides a property with the same name that is defined in the superclass. However, there are some cases where it is preferable to build up a property's value by merging the superclass property value with the subclass property's value. An example of this in use within Ember is the queryParams property of routes.
Here is some sample code showing the difference between a merged property and a normal one:
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
27
28
29
30
31
32
33
34
35
36
37
38
39
const Bar = Ember.Object.extend({
// Configure which properties are to be merged
mergedProperties: ['mergedProperty'],
someNonMergedProperty: {
nonMerged: 'superclass value of nonMerged'
},
mergedProperty: {
page: { replace: false },
limit: { replace: true }
}
});
const FooBar = Bar.extend({
someNonMergedProperty: {
completelyNonMerged: 'subclass value of nonMerged'
},
mergedProperty: {
limit: { replace: false }
}
});
let fooBar = FooBar.create();
fooBar.get('someNonMergedProperty');
// => { completelyNonMerged: 'subclass value of nonMerged' }
//
// Note the entire object, including the nonMerged property of
// the superclass object, has been replaced
fooBar.get('mergedProperty');
// => {
// page: {replace: false},
// limit: {replace: false}
// }
//
// Note the page remains from the superclass, and the
// `limit` property's value of `false` has been merged from
// the subclass.
This behavior is not available during object create calls. It is only available at extend time.
In Ember.Route the queryParams property is merged.
This feature is available for you to use throughout the Ember object model, although typical app developers are likely to use it infrequently. Since it changes expectations about behavior of properties, you should properly document its usage in each individual merged property (to not mislead your users to think they can override the property in a subclass).
Module: ember
Set this to provide an alternate class to Ember.DefaultResolver
Module: ember
The root DOM element of the Application. This can be specified as an element or a jQuery-compatible selector string.
This is the element that will be passed to the Application's, eventDispatcher, which sets up the listeners for event delegation. Every view in your application should be a child of the element you specify here. | __label__pos | 0.783532 |
PRINTF(3S) UNIX Programmer's Manual PRINTF(3S)
NAME
printf, fprintf, sprintf, vfprintf, vsprintf - formatted
output conversion
SYNOPSIS
#include <stdio.h>
char *printf(format [, arg ] ... )
char *format;
char *fprintf(stream, format [, arg ] ... )
FILE *stream;
char *format;
int sprintf(s, format [, arg ] ... )
char *s, *format;
#include <varargs.h>
char *vprintf(format, args)
char *format;
va_list args;
char *vfprintf(stream, format, args)
FILE *stream;
char *format;
va_list args;
int vsprintf(s, format, args)
char *s, *format;
va_list args;
DESCRIPTION
Printf places output on the standard output stream stdout.
Fprintf places output on the named output stream. Sprintf
places `output' in the string s, followed by the character
`\0'. Alternate forms, in which the arguments have already
been captured using the variable-length argument facilities
of varargs(3), are available under the names vprintf,
vfprintf, and vsprintf.
Each of these functions converts, formats, and prints its
arguments after the first under control of the first argu-
ment. The first argument is a character string which con-
tains two types of objects: plain characters, which are sim-
ply copied to the output stream, and conversion specifica-
tions, each of which causes conversion and printing of the
next successive arg printf.
Each conversion specification is introduced by the character
%. The remainder of the conversion specification includes
in the following order
Printed 11/26/99 August 10, 1988 1
PRINTF(3S) UNIX Programmer's Manual PRINTF(3S)
o+ a minus sign `-' which specifies left adjustment of the
converted value in the indicated field;
o+ an optional digit string specifying a field width; if
the converted value has fewer characters than the field
width it will be blank-padded on the left (or right, if
the left-adjustment indicator has been given) to make
up the field width; if the field width begins with a
zero, zero-padding will be done instead of blank-
padding;
o+ an optional period, followed by an optional digit
string giving a precision which specifies the number of
digits to appear after the decimal point, for e- and
f-conversion, or the maximum number of characters to be
printed from a string;
o+ the character l specifying that a following d, o, x, or
u corresponds to a long integer arg;
o+ a character which indicates the type of conversion to
be applied.
A field width or precision may be `*' instead of a digit
string. In this case an integer arg supplies the field
width or precision.
The conversion characters and their meanings are
dox The integer arg is converted to signed decimal,
unsigned octal, or unsigned hexadecimal notation
respectively.
f The float or double arg is converted to decimal nota-
tion in the style `[-]ddd.ddd' where the number of d's
after the decimal point is equal to the precision
specification for the argument. If the precision is
missing, 6 digits are given; if the precision is expli-
citly 0, no digits and no decimal point are printed.
e The float or double arg is converted in the style
`[-]d.ddde+dd' where there is one digit before the
decimal point and the number after is equal to the pre-
cision specification for the argument; when the preci-
sion is missing, 6 digits are produced.
g The float or double arg is printed in style d, in style
f, or in style e, whichever gives full precision in
minimum space.
c The character arg is printed.
Printed 11/26/99 August 10, 1988 2
PRINTF(3S) UNIX Programmer's Manual PRINTF(3S)
s Arg is taken to be a string (character pointer) and
characters from the string are printed until a null
character or until the number of characters indicated
by the precision specification is reached; however if
the precision is 0 or missing all characters up to a
null are printed.
u The unsigned integer arg is converted to decimal and
printed (the result will be in the range 0 through MAX-
UINT, where MAXUINT equals 4294967295 on a VAX-11 and
65535 on a PDP-11).
% Print a `%'; no argument is converted.
In no case does a non-existent or small field width cause
truncation of a field; padding takes place only if the
specified field width exceeds the actual width. Characters
generated by printf are printed as by putc(3S).
RETURN VALUE
The functions all return the number of characters printed,
or -1 if an error occurred.
EXAMPLES
To print a date and time in the form `Sunday, July 3,
10:02', where weekday and month are pointers to null-
terminated strings:
printf("%s, %s %d, %02d:%02d", weekday, month, day,
hour, min);
To print pi to 5 decimals:
printf("pi = %.5f", 4*atan(1.0));
SEE ALSO
putc(3S), scanf(3S)
BUGS
Very wide fields (>300 characters) fail.
Only sprintf and vsprintf return a count of characters
transferred.
The functions still supports %D, %O, %U and %X. Do not use
these formats, as they will be disappearing real soon now.
Printed 11/26/99 August 10, 1988 3
Generated: 2016-12-26
Generated by man2html V0.25
page hit count: 114
Valid CSS Valid XHTML 1.0 Strict | __label__pos | 0.567667 |
st_extensions.c 72.4 KB
Newer Older
1 2
/**************************************************************************
*
Jose Fonseca's avatar
Jose Fonseca committed
3
* Copyright 2007 VMware, Inc.
4
* Copyright (c) 2008 VMware, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
* All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sub license, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice (including the
* next paragraph) shall be included in all copies or substantial portions
* of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
Jose Fonseca's avatar
Jose Fonseca committed
22
* IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
23 24 25 26 27 28
* ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*
**************************************************************************/
29 30
#include "compiler/nir/nir.h"
31
#include "util/imports.h"
32 33
#include "main/context.h"
#include "main/macros.h"
34
#include "main/spirv_extensions.h"
35
#include "main/version.h"
36 37 38
#include "pipe/p_context.h"
#include "pipe/p_defines.h"
39
#include "pipe/p_screen.h"
40
#include "tgsi/tgsi_from_mesa.h"
41
#include "util/u_math.h"
42 43
#include "st_context.h"
Rob Clark's avatar
Rob Clark committed
44
#include "st_debug.h"
45
#include "st_extensions.h"
46
#include "st_format.h"
47
48 49 50 51 52 53
/*
* Note: we use these function rather than the MIN2, MAX2, CLAMP macros to
* avoid evaluating arguments (which are often function calls) more than once.
*/
54
static unsigned _min(unsigned a, unsigned b)
55 56 57 58
{
return (a < b) ? a : b;
}
59
static float _maxf(float a, float b)
60 61 62 63
{
return (a > b) ? a : b;
}
64
static int _clamp(int a, int min, int max)
65
{
66 67 68 69 70 71
if (a < min)
return min;
else if (a > max)
return max;
else
return a;
72 73 74
}
75 76 77 78
/**
* Query driver to get implementation limits.
* Note that we have to limit/clamp against Mesa's internal limits too.
*/
79
void st_init_limits(struct pipe_screen *screen,
80
struct gl_constants *c, struct gl_extensions *extensions)
81
{
82
int supported_irs;
83
unsigned sh;
84
bool can_ubo = true;
85
int temp;
86
87 88
c->MaxTextureSize = screen->get_param(screen, PIPE_CAP_MAX_TEXTURE_2D_SIZE);
c->MaxTextureSize = MIN2(c->MaxTextureSize, 1 << (MAX_TEXTURE_LEVELS - 1));
89
90
c->Max3DTextureLevels
91
= _min(screen->get_param(screen, PIPE_CAP_MAX_TEXTURE_3D_LEVELS),
92
MAX_3D_TEXTURE_LEVELS);
93
94
c->MaxCubeTextureLevels
95
= _min(screen->get_param(screen, PIPE_CAP_MAX_TEXTURE_CUBE_LEVELS),
96
MAX_CUBE_TEXTURE_LEVELS);
97
98
c->MaxTextureRectSize = _min(c->MaxTextureSize, MAX_TEXTURE_RECT_SIZE);
99
100 101 102
c->MaxArrayTextureLayers
= screen->get_param(screen, PIPE_CAP_MAX_TEXTURE_ARRAY_LAYERS);
103 104 105 106 107 108 109 110
/* Define max viewport size and max renderbuffer size in terms of
* max texture size (note: max tex RECT size = max tex 2D size).
* If this isn't true for some hardware we'll need new PIPE_CAP_ queries.
*/
c->MaxViewportWidth =
c->MaxViewportHeight =
c->MaxRenderbufferSize = c->MaxTextureRectSize;
111
c->SubPixelBits =
112
screen->get_param(screen, PIPE_CAP_RASTERIZER_SUBPIXEL_BITS);
113 114 115
c->ViewportSubpixelBits =
screen->get_param(screen, PIPE_CAP_VIEWPORT_SUBPIXEL_BITS);
116 117 118
c->MaxDrawBuffers = c->MaxColorAttachments =
_clamp(screen->get_param(screen, PIPE_CAP_MAX_RENDER_TARGETS),
1, MAX_DRAW_BUFFERS);
119
120 121 122 123 124 125 126 127 128 129 130 131 132 133
c->MaxDualSourceDrawBuffers =
_clamp(screen->get_param(screen,
PIPE_CAP_MAX_DUAL_SOURCE_RENDER_TARGETS),
0, MAX_DRAW_BUFFERS);
c->MaxLineWidth =
_maxf(1.0f, screen->get_paramf(screen, PIPE_CAPF_MAX_LINE_WIDTH));
c->MaxLineWidthAA =
_maxf(1.0f, screen->get_paramf(screen, PIPE_CAPF_MAX_LINE_WIDTH_AA));
c->MaxPointSize =
_maxf(1.0f, screen->get_paramf(screen, PIPE_CAPF_MAX_POINT_WIDTH));
c->MaxPointSizeAA =
_maxf(1.0f, screen->get_paramf(screen, PIPE_CAPF_MAX_POINT_WIDTH_AA));
134
135
c->MinPointSize = 1.0f;
136
c->MinPointSizeAA = 1.0f;
137
138 139 140
c->MaxTextureMaxAnisotropy =
_maxf(2.0f,
screen->get_paramf(screen, PIPE_CAPF_MAX_TEXTURE_ANISOTROPY));
141
142 143
c->MaxTextureLodBias =
screen->get_paramf(screen, PIPE_CAPF_MAX_TEXTURE_LOD_BIAS);
144
145 146 147
c->QuadsFollowProvokingVertexConvention =
screen->get_param(screen,
PIPE_CAP_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION);
148
149 150
c->MaxUniformBlockSize =
screen->get_shader_param(screen, PIPE_SHADER_FRAGMENT,
151
PIPE_SHADER_CAP_MAX_CONST_BUFFER_SIZE);
152 153 154 155 156
/* GL45-CTS.enhanced_layouts.ssb_member_invalid_offset_alignment fails if
* this is larger than INT_MAX - 100. Use a nicely aligned limit.
*/
c->MaxUniformBlockSize = MIN2(c->MaxUniformBlockSize, INT_MAX - 127);
157
if (c->MaxUniformBlockSize < 16384) {
158
can_ubo = false;
159 160
}
161 162
for (sh = 0; sh < PIPE_SHADER_TYPES; ++sh) {
struct gl_shader_compiler_options *options;
163
struct gl_program_constants *pc;
164 165
const nir_shader_compiler_options *nir_options = NULL;
166 167 168 169
bool prefer_nir = PIPE_SHADER_IR_NIR ==
screen->get_shader_param(screen, sh, PIPE_SHADER_CAP_PREFERRED_IR);
if (screen->get_compiler_options && prefer_nir) {
170 171 172
nir_options = (const nir_shader_compiler_options *)
screen->get_compiler_options(screen, PIPE_SHADER_IR_NIR, sh);
}
173
174 175 176 177
const gl_shader_stage stage = tgsi_processor_to_shader_stage(sh);
pc = &c->Program[stage];
options = &c->ShaderCompilerOptions[stage];
c->ShaderCompilerOptions[stage].NirOptions = nir_options;
178
179
if (sh == PIPE_SHADER_COMPUTE) {
180 181 182 183
if (!screen->get_param(screen, PIPE_CAP_COMPUTE))
continue;
supported_irs =
screen->get_shader_param(screen, sh, PIPE_SHADER_CAP_SUPPORTED_IRS);
184 185
if (!(supported_irs & ((1 << PIPE_SHADER_IR_TGSI) |
(1 << PIPE_SHADER_IR_NIR))))
186
continue;
187 188
}
189 190 191 192 193
pc->MaxTextureImageUnits =
_min(screen->get_shader_param(screen, sh,
PIPE_SHADER_CAP_MAX_TEXTURE_SAMPLERS),
MAX_TEXTURE_IMAGE_UNITS);
194 195
pc->MaxInstructions =
pc->MaxNativeInstructions =
196
screen->get_shader_param(screen, sh, PIPE_SHADER_CAP_MAX_INSTRUCTIONS);
197 198 199 200 201 202 203 204 205 206 207 208 209 210
pc->MaxAluInstructions =
pc->MaxNativeAluInstructions =
screen->get_shader_param(screen, sh,
PIPE_SHADER_CAP_MAX_ALU_INSTRUCTIONS);
pc->MaxTexInstructions =
pc->MaxNativeTexInstructions =
screen->get_shader_param(screen, sh,
PIPE_SHADER_CAP_MAX_TEX_INSTRUCTIONS);
pc->MaxTexIndirections =
pc->MaxNativeTexIndirections =
screen->get_shader_param(screen, sh,
PIPE_SHADER_CAP_MAX_TEX_INDIRECTIONS);
pc->MaxAttribs =
pc->MaxNativeAttribs =
211
screen->get_shader_param(screen, sh, PIPE_SHADER_CAP_MAX_INPUTS);
212 213
pc->MaxTemps =
pc->MaxNativeTemps =
214
screen->get_shader_param(screen, sh, PIPE_SHADER_CAP_MAX_TEMPS);
215 216
pc->MaxAddressRegs =
pc->MaxNativeAddressRegs = sh == PIPE_SHADER_VERTEX ? 1 : 0;
217 218
pc->MaxUniformComponents =
219
screen->get_shader_param(screen, sh,
220 221 222 223
PIPE_SHADER_CAP_MAX_CONST_BUFFER_SIZE) / 4;
pc->MaxUniformComponents = MIN2(pc->MaxUniformComponents,
MAX_UNIFORMS * 4);
224 225 226 227 228
/* For ARB programs, prog_src_register::Index is a signed 13-bit number.
* This gives us a limit of 4096 values - but we may need to generate
* internal values in addition to what the source program uses. So, we
* drop the limit one step lower, to 2048, to be safe.
*/
229
pc->MaxParameters =
230
pc->MaxNativeParameters = MIN2(pc->MaxUniformComponents / 4, 2048);
231 232 233 234
pc->MaxInputComponents =
screen->get_shader_param(screen, sh, PIPE_SHADER_CAP_MAX_INPUTS) * 4;
pc->MaxOutputComponents =
screen->get_shader_param(screen, sh, PIPE_SHADER_CAP_MAX_OUTPUTS) * 4;
235 236 237
pc->MaxUniformBlocks =
238 239
screen->get_shader_param(screen, sh,
PIPE_SHADER_CAP_MAX_CONST_BUFFERS);
240 241
if (pc->MaxUniformBlocks)
pc->MaxUniformBlocks -= 1; /* The first one is for ordinary uniforms. */
242
pc->MaxUniformBlocks = _min(pc->MaxUniformBlocks, MAX_UNIFORM_BUFFERS);
243
244 245 246
pc->MaxCombinedUniformComponents =
pc->MaxUniformComponents +
(uint64_t)c->MaxUniformBlockSize / 4 * pc->MaxUniformBlocks;
247
248 249 250 251
pc->MaxShaderStorageBlocks =
screen->get_shader_param(screen, sh,
PIPE_SHADER_CAP_MAX_SHADER_BUFFERS);
252 253 254 255 256 257 258 259
temp = screen->get_shader_param(screen, sh, PIPE_SHADER_CAP_MAX_HW_ATOMIC_COUNTERS);
if (temp) {
/*
* for separate atomic counters get the actual hw limits
* per stage on atomic counters and buffers
*/
pc->MaxAtomicCounters = temp;
pc->MaxAtomicBuffers = screen->get_shader_param(screen, sh, PIPE_SHADER_CAP_MAX_HW_ATOMIC_COUNTER_BUFFERS);
260
} else if (pc->MaxShaderStorageBlocks) {
261
pc->MaxAtomicCounters = MAX_ATOMIC_COUNTERS;
262 263 264 265 266 267
/*
* without separate atomic counters, reserve half of the available
* SSBOs for atomic buffers, and the other half for normal SSBOs.
*/
pc->MaxAtomicBuffers = pc->MaxShaderStorageBlocks / 2;
pc->MaxShaderStorageBlocks -= pc->MaxAtomicBuffers;
268
}
269 270 271
pc->MaxImageUniforms = screen->get_shader_param(
screen, sh, PIPE_SHADER_CAP_MAX_SHADER_IMAGES);
272 273 274
/* Gallium doesn't really care about local vs. env parameters so use the
* same limits.
*/
275 276
pc->MaxLocalParams = MIN2(pc->MaxParameters, MAX_PROGRAM_LOCAL_PARAMS);
pc->MaxEnvParams = MIN2(pc->MaxParameters, MAX_PROGRAM_ENV_PARAMS);
277
278 279 280 281 282 283 284
if (screen->get_shader_param(screen, sh, PIPE_SHADER_CAP_INTEGERS)) {
pc->LowInt.RangeMin = 31;
pc->LowInt.RangeMax = 30;
pc->LowInt.Precision = 0;
pc->MediumInt = pc->HighInt = pc->LowInt;
}
285
/* TODO: make these more fine-grained if anyone needs it */
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
options->MaxIfDepth =
screen->get_shader_param(screen, sh,
PIPE_SHADER_CAP_MAX_CONTROL_FLOW_DEPTH);
options->EmitNoLoops =
!screen->get_shader_param(screen, sh,
PIPE_SHADER_CAP_MAX_CONTROL_FLOW_DEPTH);
options->EmitNoMainReturn =
!screen->get_shader_param(screen, sh, PIPE_SHADER_CAP_SUBROUTINES);
options->EmitNoCont =
!screen->get_shader_param(screen, sh,
PIPE_SHADER_CAP_TGSI_CONT_SUPPORTED);
options->EmitNoIndirectInput =
!screen->get_shader_param(screen, sh,
PIPE_SHADER_CAP_INDIRECT_INPUT_ADDR);
options->EmitNoIndirectOutput =
!screen->get_shader_param(screen, sh,
PIPE_SHADER_CAP_INDIRECT_OUTPUT_ADDR);
options->EmitNoIndirectTemp =
!screen->get_shader_param(screen, sh,
PIPE_SHADER_CAP_INDIRECT_TEMP_ADDR);
options->EmitNoIndirectUniform =
!screen->get_shader_param(screen, sh,
PIPE_SHADER_CAP_INDIRECT_CONST_ADDR);
311
312 313
if (pc->MaxNativeInstructions &&
(options->EmitNoIndirectUniform || pc->MaxUniformBlocks < 12)) {
314
can_ubo = false;
315 316
}
Brian Paul's avatar
Brian Paul committed
317
if (options->EmitNoLoops)
318 319 320 321
options->MaxUnrollIterations =
MIN2(screen->get_shader_param(screen, sh,
PIPE_SHADER_CAP_MAX_INSTRUCTIONS),
65536);
322
else
323 324 325
options->MaxUnrollIterations =
screen->get_shader_param(screen, sh,
PIPE_SHADER_CAP_MAX_UNROLL_ITERATIONS_HINT);
326
327 328 329
if (!screen->get_param(screen, PIPE_CAP_NIR_COMPACT_ARRAYS))
options->LowerCombinedClipCullDistance = true;
330 331 332 333
/* NIR can do the lowering on our behalf and we'll get better results
* because it can actually optimize SSBO access.
*/
options->LowerBufferInterfaceBlocks = !prefer_nir;
334 335 336 337
if (sh == MESA_SHADER_VERTEX) {
if (screen->get_param(screen, PIPE_CAP_VIEWPORT_TRANSFORM_LOWERED))
options->LowerBuiltinVariablesXfb |= VARYING_BIT_POS;
338 339
if (screen->get_param(screen, PIPE_CAP_PSIZ_CLAMPED))
options->LowerBuiltinVariablesXfb |= VARYING_BIT_PSIZ;
340
}
341 342 343 344 345 346
/* Initialize lower precision shader compiler option based on
* the value of PIPE_SHADER_CAP_FP16.
*/
options->LowerPrecision =
screen->get_shader_param(screen, sh, PIPE_SHADER_CAP_FP16);
347
}
348
349 350 351 352 353 354 355
c->MaxUserAssignableUniformLocations =
c->Program[MESA_SHADER_VERTEX].MaxUniformComponents +
c->Program[MESA_SHADER_TESS_CTRL].MaxUniformComponents +
c->Program[MESA_SHADER_TESS_EVAL].MaxUniformComponents +
c->Program[MESA_SHADER_GEOMETRY].MaxUniformComponents +
c->Program[MESA_SHADER_FRAGMENT].MaxUniformComponents;
356 357
c->GLSLOptimizeConservatively =
screen->get_param(screen, PIPE_CAP_GLSL_OPTIMIZE_CONSERVATIVELY);
358 359
c->GLSLLowerConstArrays =
screen->get_param(screen, PIPE_CAP_PREFER_IMM_ARRAYS_AS_CONSTBUF);
360 361
c->GLSLTessLevelsAsInputs =
screen->get_param(screen, PIPE_CAP_GLSL_TESS_LEVELS_AS_INPUTS);
362 363
c->LowerTessLevel =
!screen->get_param(screen, PIPE_CAP_NIR_COMPACT_ARRAYS);
364 365
c->LowerCsDerivedVariables =
!screen->get_param(screen, PIPE_CAP_CS_DERIVED_SYSTEM_VALUES_SUPPORTED);
366 367
c->PrimitiveRestartForPatches =
screen->get_param(screen, PIPE_CAP_PRIMITIVE_RESTART_FOR_PATCHES);
368
369 370
c->MaxCombinedTextureImageUnits =
_min(c->Program[MESA_SHADER_VERTEX].MaxTextureImageUnits +
371 372
c->Program[MESA_SHADER_TESS_CTRL].MaxTextureImageUnits +
c->Program[MESA_SHADER_TESS_EVAL].MaxTextureImageUnits +
373
c->Program[MESA_SHADER_GEOMETRY].MaxTextureImageUnits +
374 375
c->Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits +
c->Program[MESA_SHADER_COMPUTE].MaxTextureImageUnits,
376 377
MAX_COMBINED_TEXTURE_IMAGE_UNITS);
378 379
/* This depends on program constants. */
c->MaxTextureCoordUnits
380 381
= _min(c->Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits,
MAX_TEXTURE_COORD_UNITS);
382
383 384 385
c->MaxTextureUnits =
_min(c->Program[MESA_SHADER_FRAGMENT].MaxTextureImageUnits,
c->MaxTextureCoordUnits);
386
387 388
c->Program[MESA_SHADER_VERTEX].MaxAttribs =
MIN2(c->Program[MESA_SHADER_VERTEX].MaxAttribs, 16);
389
390
c->MaxVarying = screen->get_param(screen, PIPE_CAP_MAX_VARYINGS);
391
c->MaxVarying = MIN2(c->MaxVarying, MAX_VARYING);
392 393 394 395
c->MaxGeometryOutputVertices =
screen->get_param(screen, PIPE_CAP_MAX_GEOMETRY_OUTPUT_VERTICES);
c->MaxGeometryTotalOutputComponents =
screen->get_param(screen, PIPE_CAP_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS);
396 397
c->MaxGeometryShaderInvocations =
screen->get_param(screen, PIPE_CAP_MAX_GS_INVOCATIONS);
398
c->MaxTessPatchComponents =
399
MIN2(screen->get_param(screen, PIPE_CAP_MAX_SHADER_PATCH_VARYINGS),
400
MAX_VARYING) * 4;
401
402 403 404 405
c->MinProgramTexelOffset =
screen->get_param(screen, PIPE_CAP_MIN_TEXEL_OFFSET);
c->MaxProgramTexelOffset =
screen->get_param(screen, PIPE_CAP_MAX_TEXEL_OFFSET);
406
407 408 409 410 411 412
c->MaxProgramTextureGatherComponents =
screen->get_param(screen, PIPE_CAP_MAX_TEXTURE_GATHER_COMPONENTS);
c->MinProgramTextureGatherOffset =
screen->get_param(screen, PIPE_CAP_MIN_TEXTURE_GATHER_OFFSET);
c->MaxProgramTextureGatherOffset =
screen->get_param(screen, PIPE_CAP_MAX_TEXTURE_GATHER_OFFSET);
413
414
c->MaxTransformFeedbackBuffers =
415
screen->get_param(screen, PIPE_CAP_MAX_STREAM_OUTPUT_BUFFERS);
416 417
c->MaxTransformFeedbackBuffers = MIN2(c->MaxTransformFeedbackBuffers,
MAX_FEEDBACK_BUFFERS);
418 419 420
c->MaxTransformFeedbackSeparateComponents =
screen->get_param(screen, PIPE_CAP_MAX_STREAM_OUTPUT_SEPARATE_COMPONENTS);
c->MaxTransformFeedbackInterleavedComponents =
421 422
screen->get_param(screen,
PIPE_CAP_MAX_STREAM_OUTPUT_INTERLEAVED_COMPONENTS);
423 424 425 426 427
c->MaxVertexStreams =
MAX2(1, screen->get_param(screen, PIPE_CAP_MAX_VERTEX_STREAMS));
/* The vertex stream must fit into pipe_stream_output_info::stream */
assert(c->MaxVertexStreams <= 4);
428
429 430 431
c->MaxVertexAttribStride
= screen->get_param(screen, PIPE_CAP_MAX_VERTEX_ATTRIB_STRIDE);
432 433 434 435 436 437
/* The value cannot be larger than that since pipe_vertex_buffer::src_offset
* is only 16 bits.
*/
temp = screen->get_param(screen, PIPE_CAP_MAX_VERTEX_ELEMENT_SRC_OFFSET);
c->MaxVertexAttribRelativeOffset = MIN2(0xffff, temp);
438
c->StripTextureBorder = GL_TRUE;
439 440 441 442
c->GLSLSkipStrictMaxUniformLimitCheck =
screen->get_param(screen, PIPE_CAP_TGSI_CAN_COMPACT_CONSTANTS);
443 444 445
c->UniformBufferOffsetAlignment =
screen->get_param(screen, PIPE_CAP_CONSTANT_BUFFER_OFFSET_ALIGNMENT);
446
if (can_ubo) {
447
extensions->ARB_uniform_buffer_object = GL_TRUE;
448
c->MaxCombinedUniformBlocks = c->MaxUniformBufferBindings =
449
c->Program[MESA_SHADER_VERTEX].MaxUniformBlocks +
450 451
c->Program[MESA_SHADER_TESS_CTRL].MaxUniformBlocks +
c->Program[MESA_SHADER_TESS_EVAL].MaxUniformBlocks +
452
c->Program[MESA_SHADER_GEOMETRY].MaxUniformBlocks +
453 454
c->Program[MESA_SHADER_FRAGMENT].MaxUniformBlocks +
c->Program[MESA_SHADER_COMPUTE].MaxUniformBlocks;
455
assert(c->MaxCombinedUniformBlocks <= MAX_COMBINED_UNIFORM_BUFFERS);
456
}
457 458 459
c->GLSLFragCoordIsSysVal =
screen->get_param(screen, PIPE_CAP_TGSI_FS_POSITION_IS_SYSVAL);
460 461
c->GLSLPointCoordIsSysVal =
screen->get_param(screen, PIPE_CAP_TGSI_FS_POINT_IS_SYSVAL);
462 463
c->GLSLFrontFacingIsSysVal =
screen->get_param(screen, PIPE_CAP_TGSI_FS_FACE_IS_INTEGER_SYSVAL);
464
465 466
/* GL_ARB_get_program_binary */
if (screen->get_disk_shader_cache && screen->get_disk_shader_cache(screen))
467 468
c->NumProgramBinaryFormats = 1;
469
c->MaxAtomicBufferBindings =
470 471 472
c->Program[MESA_SHADER_FRAGMENT].MaxAtomicBuffers;
c->MaxAtomicBufferSize =
c->Program[MESA_SHADER_FRAGMENT].MaxAtomicCounters * ATOMIC_COUNTER_SIZE;
473
474 475 476 477 478
c->MaxCombinedAtomicBuffers =
MIN2(screen->get_param(screen,
PIPE_CAP_MAX_COMBINED_HW_ATOMIC_COUNTER_BUFFERS),
MAX_COMBINED_ATOMIC_BUFFERS);
if (!c->MaxCombinedAtomicBuffers) {
479
c->MaxCombinedAtomicBuffers =
480 481 482 483 484
c->Program[MESA_SHADER_VERTEX].MaxAtomicBuffers +
c->Program[MESA_SHADER_TESS_CTRL].MaxAtomicBuffers +
c->Program[MESA_SHADER_TESS_EVAL].MaxAtomicBuffers +
c->Program[MESA_SHADER_GEOMETRY].MaxAtomicBuffers +
c->Program[MESA_SHADER_FRAGMENT].MaxAtomicBuffers;
485 486
assert(c->MaxCombinedAtomicBuffers <= MAX_COMBINED_ATOMIC_BUFFERS);
}
487
488 489 490 491 492
c->MaxCombinedAtomicCounters =
screen->get_param(screen, PIPE_CAP_MAX_COMBINED_HW_ATOMIC_COUNTERS);
if (!c->MaxCombinedAtomicCounters)
c->MaxCombinedAtomicCounters = MAX_ATOMIC_COUNTERS;
493
if (c->MaxCombinedAtomicBuffers > 0) {
494
extensions->ARB_shader_atomic_counters = GL_TRUE;
495 496
extensions->ARB_shader_atomic_counter_ops = GL_TRUE;
}
497 498 499 500 501
c->MaxCombinedShaderOutputResources = c->MaxDrawBuffers;
c->ShaderStorageBufferOffsetAlignment =
screen->get_param(screen, PIPE_CAP_SHADER_BUFFER_OFFSET_ALIGNMENT);
if (c->ShaderStorageBufferOffsetAlignment) {
502 503 504 505
c->MaxCombinedShaderStorageBlocks =
MIN2(screen->get_param(screen, PIPE_CAP_MAX_COMBINED_SHADER_BUFFERS),
MAX_COMBINED_SHADER_STORAGE_BUFFERS);
if (!c->MaxCombinedShaderStorageBlocks) {
506 507 508 509 510 511 512 513 514 515
c->MaxCombinedShaderStorageBlocks =
c->Program[MESA_SHADER_VERTEX].MaxShaderStorageBlocks +
c->Program[MESA_SHADER_TESS_CTRL].MaxShaderStorageBlocks +
c->Program[MESA_SHADER_TESS_EVAL].MaxShaderStorageBlocks +
c->Program[MESA_SHADER_GEOMETRY].MaxShaderStorageBlocks +
c->Program[MESA_SHADER_FRAGMENT].MaxShaderStorageBlocks;
assert(c->MaxCombinedShaderStorageBlocks < MAX_COMBINED_SHADER_STORAGE_BUFFERS);
}
c->MaxShaderStorageBufferBindings = c->MaxCombinedShaderStorageBlocks;
516 517
c->MaxCombinedShaderOutputResources +=
c->MaxCombinedShaderStorageBlocks;
518 519
c->MaxShaderStorageBlockSize =
screen->get_param(screen, PIPE_CAP_MAX_SHADER_BUFFER_SIZE);
520
extensions->ARB_shader_storage_buffer_object = GL_TRUE;
521
}
522 523 524 525 526 527
c->MaxCombinedImageUniforms =
c->Program[MESA_SHADER_VERTEX].MaxImageUniforms +
c->Program[MESA_SHADER_TESS_CTRL].MaxImageUniforms +
c->Program[MESA_SHADER_TESS_EVAL].MaxImageUniforms +
c->Program[MESA_SHADER_GEOMETRY].MaxImageUniforms +
528 529
c->Program[MESA_SHADER_FRAGMENT].MaxImageUniforms +
c->Program[MESA_SHADER_COMPUTE].MaxImageUniforms;
530
c->MaxCombinedShaderOutputResources += c->MaxCombinedImageUniforms;
531 532 533 534 535
c->MaxImageUnits = MAX_IMAGE_UNITS;
if (c->MaxCombinedImageUniforms) {
extensions->ARB_shader_image_load_store = GL_TRUE;
extensions->ARB_shader_image_size = GL_TRUE;
}
536 537 538 539 540 541 542 543 544 545 546 547
/* ARB_framebuffer_no_attachments */
c->MaxFramebufferWidth = c->MaxViewportWidth;
c->MaxFramebufferHeight = c->MaxViewportHeight;
/* NOTE: we cheat here a little by assuming that
* PIPE_CAP_MAX_TEXTURE_ARRAY_LAYERS has the same
* number of layers as we need, although we technically
* could have more the generality is not really useful
* in practicality.
*/
c->MaxFramebufferLayers =
screen->get_param(screen, PIPE_CAP_MAX_TEXTURE_ARRAY_LAYERS);
548 549 550
c->MaxWindowRectangles =
screen->get_param(screen, PIPE_CAP_MAX_WINDOW_RECTANGLES);
551 552 553
c->SparseBufferPageSize =
screen->get_param(screen, PIPE_CAP_SPARSE_BUFFER_PAGE_SIZE);
554 555 556
c->AllowMappedBuffersDuringExecution =
screen->get_param(screen, PIPE_CAP_ALLOW_MAPPED_BUFFERS_DURING_EXECUTION);
557 558 559
c->UseSTD430AsDefaultPacking =
screen->get_param(screen, PIPE_CAP_LOAD_CONSTBUF);
560
561 562 563 564 565 566 567 568 569 570
c->MaxSubpixelPrecisionBiasBits =
screen->get_param(screen, PIPE_CAP_MAX_CONSERVATIVE_RASTER_SUBPIXEL_PRECISION_BIAS);
c->ConservativeRasterDilateRange[0] =
screen->get_paramf(screen, PIPE_CAPF_MIN_CONSERVATIVE_RASTER_DILATE);
c->ConservativeRasterDilateRange[1] =
screen->get_paramf(screen, PIPE_CAPF_MAX_CONSERVATIVE_RASTER_DILATE);
c->ConservativeRasterDilateGranularity =
screen->get_paramf(screen, PIPE_CAPF_CONSERVATIVE_RASTER_DILATE_GRANULARITY);
571 572 573 574
/* limit the max combined shader output resources to a driver limit */
temp = screen->get_param(screen, PIPE_CAP_MAX_COMBINED_SHADER_OUTPUT_RESOURCES);
if (temp > 0 && c->MaxCombinedShaderOutputResources > temp)
c->MaxCombinedShaderOutputResources = temp;
575 576 577
c->VertexBufferOffsetIsInt32 =
screen->get_param(screen, PIPE_CAP_SIGNED_VERTEX_BUFFER_OFFSET);
578 579 580
c->MultiDrawWithUserIndices =
screen->get_param(screen, PIPE_CAP_DRAW_INFO_START_WITH_USER_INDICES);
581 582 583
c->glBeginEndBufferSize =
screen->get_param(screen, PIPE_CAP_GL_BEGIN_END_BUFFER_SIZE);
584 585 586
}
587 588 589 590 591 592 593 594 595 596 597 598
/**
* Given a member \c x of struct gl_extensions, return offset of
* \c x in bytes.
*/
#define o(x) offsetof(struct gl_extensions, x)
struct st_extension_cap_mapping {
int extension_offset;
int cap;
};
599 600
struct st_extension_format_mapping {
int extension_offset[2];
Ilia Mirkin's avatar
Ilia Mirkin committed
601
enum pipe_format format[32];
602 603 604 605 606 607 608 609 610 611 612 613 614
/* If TRUE, at least one format must be supported for the extensions to be
* advertised. If FALSE, all the formats must be supported. */
GLboolean need_at_least_one;
};
/**
* Enable extensions if certain pipe formats are supported by the driver.
* What extensions will be enabled and what formats must be supported is
* described by the array of st_extension_format_mapping.
*
* target and bind_flags are passed to is_format_supported.
*/
615 616 617 618 619 620 621
static void
init_format_extensions(struct pipe_screen *screen,
struct gl_extensions *extensions,
const struct st_extension_format_mapping *mapping,
unsigned num_mappings,
enum pipe_texture_target target,
unsigned bind_flags)
622
{
623
GLboolean *extension_table = (GLboolean *) extensions;
624 625
unsigned i;
int j;
626 627
int num_formats = ARRAY_SIZE(mapping->format);
int num_ext = ARRAY_SIZE(mapping->extension_offset);
628 629 630 631 632 633 634
for (i = 0; i < num_mappings; i++) {
int num_supported = 0;
/* Examine each format in the list. */
for (j = 0; j < num_formats && mapping[i].format[j]; j++) {
if (screen->is_format_supported(screen, mapping[i].format[j],
635
target, 0, 0, bind_flags)) {
636 637 638 639 640 641 642 643 644 645 646
num_supported++;
}
}
if (!num_supported ||
(!mapping[i].need_at_least_one && num_supported != j)) {
continue;
}
/* Enable all extensions in the list. */
for (j = 0; j < num_ext && mapping[i].extension_offset[j]; j++)
647 648 649 650 651 652 653 654 655 656 657 658
extension_table[mapping[i].extension_offset[j]] = GL_TRUE;
}
}
/**
* Given a list of formats and bind flags, return the maximum number
* of samples supported by any of those formats.
*/
static unsigned
get_max_samples_for_formats(struct pipe_screen *screen,
unsigned num_formats,
659
const enum pipe_format *formats,
660 661 662 663 664 665 666 667
unsigned max_samples,
unsigned bind)
{
unsigned i, f;
for (i = max_samples; i > 0; --i) {
for (f = 0; f < num_formats; f++) {
if (screen->is_format_supported(screen, formats[f],
668
PIPE_TEXTURE_2D, i, i, bind)) {
669 670 671
return i;
}
}
672
}
673
return 0;
674
}
675
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
static unsigned
get_max_samples_for_formats_advanced(struct pipe_screen *screen,
unsigned num_formats,
const enum pipe_format *formats,
unsigned max_samples,
unsigned num_storage_samples,
unsigned bind)
{
unsigned i, f;
for (i = max_samples; i > 0; --i) {
for (f = 0; f < num_formats; f++) {
if (screen->is_format_supported(screen, formats[f], PIPE_TEXTURE_2D,
i, num_storage_samples, bind)) {
return i;
}
}
}
return 0;
}
696
697
/**
698 699 700 701 702
* Use pipe_screen::get_param() to query PIPE_CAP_ values to determine
* which GL extensions are supported.
* Quite a few extensions are always supported because they are standard
* features or can be built on top of other gallium features.
* Some fine tuning may still be needed.
703
*/
704 705 706
void st_init_extensions(struct pipe_screen *screen,
struct gl_constants *consts,
struct gl_extensions *extensions,
707 708
struct st_config_options *options,
gl_api api)
709
{
710
unsigned i;
711
GLboolean *extension_table = (GLboolean *) extensions;
712 713
static const struct st_extension_cap_mapping cap_mapping[] = {
714
{ o(ARB_base_instance), PIPE_CAP_START_INSTANCE },
715
{ o(ARB_bindless_texture), PIPE_CAP_BINDLESS_TEXTURE },
716
{ o(ARB_buffer_storage), PIPE_CAP_BUFFER_MAP_PERSISTENT_COHERENT },
717
{ o(ARB_clear_texture), PIPE_CAP_CLEAR_TEXTURE },
718
{ o(ARB_clip_control), PIPE_CAP_CLIP_HALFZ },
719
{ o(ARB_color_buffer_float), PIPE_CAP_VERTEX_COLOR_UNCLAMPED },
720
{ o(ARB_conditional_render_inverted), PIPE_CAP_CONDITIONAL_RENDER_INVERTED },
721
{ o(ARB_copy_image), PIPE_CAP_COPY_BETWEEN_COMPRESSED_AND_PLAIN_FORMATS },
722
{ o(OES_copy_image), PIPE_CAP_COPY_BETWEEN_COMPRESSED_AND_PLAIN_FORMATS },
Dave Airlie's avatar
Dave Airlie committed
723
{ o(ARB_cull_distance), PIPE_CAP_CULL_DISTANCE },
724
{ o(ARB_depth_clamp), PIPE_CAP_DEPTH_CLIP_DISABLE },
725
{ o(ARB_derivative_control), PIPE_CAP_TGSI_FS_FINE_DERIVATIVE },
726
{ o(ARB_draw_buffers_blend), PIPE_CAP_INDEP_BLEND_FUNC },
727
{ o(ARB_draw_indirect), PIPE_CAP_DRAW_INDIRECT },
728
{ o(ARB_draw_instanced), PIPE_CAP_TGSI_INSTANCEID },
729
{ o(ARB_fragment_program_shadow), PIPE_CAP_TEXTURE_SHADOW_MAP },
730
{ o(ARB_framebuffer_object), PIPE_CAP_MIXED_FRAMEBUFFER_SIZES },
731
{ o(ARB_gpu_shader_int64), PIPE_CAP_INT64 },
732
{ o(ARB_gl_spirv), PIPE_CAP_GL_SPIRV },
733
{ o(ARB_indirect_parameters), PIPE_CAP_MULTI_DRAW_INDIRECT_PARAMS },
734 735 736
{ o(ARB_instanced_arrays), PIPE_CAP_VERTEX_ELEMENT_INSTANCE_DIVISOR },
{ o(ARB_occlusion_query), PIPE_CAP_OCCLUSION_QUERY },
{ o(ARB_occlusion_query2), PIPE_CAP_OCCLUSION_QUERY },
737
{ o(ARB_pipeline_statistics_query), PIPE_CAP_QUERY_PIPELINE_STATISTICS },
738
{ o(ARB_pipeline_statistics_query), PIPE_CAP_QUERY_PIPELINE_STATISTICS_SINGLE },
739
{ o(ARB_point_sprite), PIPE_CAP_POINT_SPRITE },
740
{ o(ARB_polygon_offset_clamp), PIPE_CAP_POLYGON_OFFSET_CLAMP },
741
{ o(ARB_post_depth_coverage), PIPE_CAP_POST_DEPTH_COVERAGE },
742
{ o(ARB_query_buffer_object), PIPE_CAP_QUERY_BUFFER_OBJECT },
743
{ o(ARB_robust_buffer_access_behavior), PIPE_CAP_ROBUST_BUFFER_ACCESS_BEHAVIOR },
744
{ o(ARB_sample_shading), PIPE_CAP_SAMPLE_SHADING },
745
{ o(ARB_sample_locations), PIPE_CAP_PROGRAMMABLE_SAMPLE_LOCATIONS },
746
{ o(ARB_seamless_cube_map), PIPE_CAP_SEAMLESS_CUBE_MAP },
747
{ o(ARB_shader_ballot), PIPE_CAP_TGSI_BALLOT },
748
{ o(ARB_shader_clock), PIPE_CAP_TGSI_CLOCK },
749
{ o(ARB_shader_draw_parameters), PIPE_CAP_DRAW_PARAMETERS },
750
{ o(ARB_shader_group_vote), PIPE_CAP_TGSI_VOTE },
751
{ o(EXT_shader_image_load_formatted), PIPE_CAP_IMAGE_LOAD_FORMATTED },
752
{ o(EXT_shader_image_load_store), PIPE_CAP_TGSI_ATOMINC_WRAP },
753
{ o(ARB_shader_stencil_export), PIPE_CAP_SHADER_STENCIL_EXPORT },
754
{ o(ARB_shader_texture_image_samples), PIPE_CAP_TGSI_TXQS },
755
{ o(ARB_shader_texture_lod), PIPE_CAP_FRAGMENT_SHADER_TEXTURE_LOD },
756
{ o(ARB_shadow), PIPE_CAP_TEXTURE_SHADOW_MAP },
757
{ o(ARB_sparse_buffer), PIPE_CAP_SPARSE_BUFFER_PAGE_SIZE },
758
{ o(ARB_spirv_extensions), PIPE_CAP_GL_SPIRV },
759
{ o(ARB_texture_buffer_object), PIPE_CAP_TEXTURE_BUFFER_OBJECTS },
760
{ o(ARB_texture_cube_map_array), PIPE_CAP_CUBE_MAP_ARRAY },
761
{ o(ARB_texture_gather), PIPE_CAP_MAX_TEXTURE_GATHER_COMPONENTS },
762
{ o(ARB_texture_mirror_clamp_to_edge), PIPE_CAP_TEXTURE_MIRROR_CLAMP_TO_EDGE },
763
{ o(ARB_texture_multisample), PIPE_CAP_TEXTURE_MULTISAMPLE },
764
{ o(ARB_texture_non_power_of_two), PIPE_CAP_NPOT_TEXTURES },
765 766
{ o(ARB_texture_query_lod), PIPE_CAP_TEXTURE_QUERY_LOD },
{ o(ARB_texture_view), PIPE_CAP_SAMPLER_VIEW_TARGET },
767
{ o(ARB_timer_query), PIPE_CAP_QUERY_TIMESTAMP },
768
{ o(ARB_transform_feedback2), PIPE_CAP_STREAM_OUTPUT_PAUSE_RESUME },
769
{ o(ARB_transform_feedback3), PIPE_CAP_STREAM_OUTPUT_INTERLEAVE_BUFFERS },
770
{ o(ARB_transform_feedback_overflow_query), PIPE_CAP_QUERY_SO_OVERFLOW },
771
{ o(ARB_fragment_shader_interlock), PIPE_CAP_FRAGMENT_SHADER_INTERLOCK },
772 773
{ o(EXT_blend_equation_separate), PIPE_CAP_BLEND_EQUATION_SEPARATE },
774
{ o(EXT_demote_to_helper_invocation), PIPE_CAP_DEMOTE_TO_HELPER_INVOCATION },
775
{ o(EXT_depth_bounds_test), PIPE_CAP_DEPTH_BOUNDS_TEST },
776
{ o(EXT_disjoint_timer_query), PIPE_CAP_QUERY_TIMESTAMP },
777
{ o(EXT_draw_buffers2), PIPE_CAP_INDEP_BLEND_ENABLE },
778 779
{ o(EXT_memory_object), PIPE_CAP_MEMOBJ },
{ o(EXT_memory_object_fd), PIPE_CAP_MEMOBJ },
780
{ o(EXT_multisampled_render_to_texture), PIPE_CAP_SURFACE_SAMPLE_COUNT },
781 782
{ o(EXT_semaphore), PIPE_CAP_FENCE_SIGNAL },
{ o(EXT_semaphore_fd), PIPE_CAP_FENCE_SIGNAL },
783
{ o(EXT_shader_samples_identical), PIPE_CAP_SHADER_SAMPLES_IDENTICAL },
784 785 786
{ o(EXT_texture_array), PIPE_CAP_MAX_TEXTURE_ARRAY_LAYERS },
{ o(EXT_texture_filter_anisotropic), PIPE_CAP_ANISOTROPIC_FILTER },
{ o(EXT_texture_mirror_clamp), PIPE_CAP_TEXTURE_MIRROR_CLAMP },
787
{ o(EXT_texture_shadow_lod), PIPE_CAP_TEXTURE_SHADOW_LOD },
788 789
{ o(EXT_texture_swizzle), PIPE_CAP_TEXTURE_SWIZZLE },
{ o(EXT_transform_feedback), PIPE_CAP_MAX_STREAM_OUTPUT_BUFFERS },
790
{ o(EXT_window_rectangles), PIPE_CAP_MAX_WINDOW_RECTANGLES },
791
792
{ o(AMD_depth_clamp_separate), PIPE_CAP_DEPTH_CLIP_DISABLE_SEPARATE },
793
{ o(AMD_framebuffer_multisample_advanced), PIPE_CAP_FRAMEBUFFER_MSAA_CONSTRAINTS },
794
{ o(AMD_pinned_memory), PIPE_CAP_RESOURCE_FROM_USER_MEMORY },
795
{ o(ATI_meminfo), PIPE_CAP_QUERY_MEMORY_INFO },
796 797
{ o(AMD_seamless_cubemap_per_texture), PIPE_CAP_SEAMLESS_CUBE_MAP_PER_TEXTURE },
{ o(ATI_texture_mirror_once), PIPE_CAP_TEXTURE_MIRROR_CLAMP },
798
{ o(INTEL_conservative_rasterization), PIPE_CAP_CONSERVATIVE_RASTER_INNER_COVERAGE },
799
{ o(INTEL_shader_atomic_float_minmax), PIPE_CAP_ATOMIC_FLOAT_MINMAX },
800
{ o(MESA_tile_raster_order), PIPE_CAP_TILE_RASTER_ORDER },
801
{ o(NV_compute_shader_derivatives), PIPE_CAP_COMPUTE_SHADER_DERIVATIVES },
802
{ o(NV_conditional_render), PIPE_CAP_CONDITIONAL_RENDER },
803
{ o(NV_fill_rectangle), PIPE_CAP_POLYGON_MODE_FILL_RECTANGLE },
804
{ o(NV_primitive_restart), PIPE_CAP_PRIMITIVE_RESTART },
805
{ o(NV_shader_atomic_float), PIPE_CAP_TGSI_ATOMFADD },
806
{ o(NV_texture_barrier), PIPE_CAP_TEXTURE_BARRIER },
807
{ o(NV_viewport_swizzle), PIPE_CAP_VIEWPORT_SWIZZLE },
808
{ o(NVX_gpu_memory_info), PIPE_CAP_QUERY_MEMORY_INFO },
809 810
/* GL_NV_point_sprite is not supported by gallium because we don't
* support the GL_POINT_SPRITE_R_MODE_NV option. */
811
812
{ o(OES_standard_derivatives), PIPE_CAP_FRAGMENT_SHADER_DERIVATIVES },
813 814
{ o(OES_texture_float_linear), PIPE_CAP_TEXTURE_FLOAT_LINEAR },
{ o(OES_texture_half_float_linear), PIPE_CAP_TEXTURE_HALF_FLOAT_LINEAR },
815
{ o(OES_texture_view), PIPE_CAP_SAMPLER_VIEW_TARGET },
816
{ o(INTEL_blackhole_render), PIPE_CAP_FRONTEND_NOOP, },
817
};
818
819 820
/* Required: render target and sampler support */
static const struct st_extension_format_mapping rendertarget_mapping[] = {
821 822 823 824 825 826
{ { o(OES_texture_float) },
{ PIPE_FORMAT_R32G32B32A32_FLOAT } },
{ { o(OES_texture_half_float) },
{ PIPE_FORMAT_R16G16B16A16_FLOAT } },
827
{ { o(ARB_texture_rgb10_a2ui) },
828 829 830
{ PIPE_FORMAT_R10G10B10A2_UINT,
PIPE_FORMAT_B10G10R10A2_UINT },
GL_TRUE }, /* at least one format must be supported */
831
832
{ { o(EXT_sRGB) },
833
{ PIPE_FORMAT_A8B8G8R8_SRGB,
834 835
PIPE_FORMAT_B8G8R8A8_SRGB,
PIPE_FORMAT_R8G8B8A8_SRGB },
836 837 838 839 840 841 842 843
GL_TRUE }, /* at least one format must be supported */
{ { o(EXT_packed_float) },
{ PIPE_FORMAT_R11G11B10_FLOAT } },
{ { o(EXT_texture_integer) },
{ PIPE_FORMAT_R32G32B32A32_UINT,
PIPE_FORMAT_R32G32B32A32_SINT } },
844 845 846 847
{ { o(ARB_texture_rg) },
{ PIPE_FORMAT_R8_UNORM,
PIPE_FORMAT_R8G8_UNORM } },
848
849 850 851 852 853
{ { o(EXT_texture_norm16) },
{ PIPE_FORMAT_R16_UNORM,
PIPE_FORMAT_R16G16_UNORM,
PIPE_FORMAT_R16G16B16A16_UNORM } },
854 855 856 857 858 859 860
{ { o(EXT_render_snorm) },
{ PIPE_FORMAT_R8_SNORM,
PIPE_FORMAT_R8G8_SNORM,
PIPE_FORMAT_R8G8B8A8_SNORM,
PIPE_FORMAT_R16_SNORM,
PIPE_FORMAT_R16G16_SNORM,
PIPE_FORMAT_R16G16B16A16_SNORM } },
861 862
};
863 864 865 866 867 868
/* Required: render target, sampler, and blending */
static const struct st_extension_format_mapping rt_blendable[] = {
{ { o(EXT_float_blend) },
{ PIPE_FORMAT_R32G32B32A32_FLOAT } },
};
869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890
/* Required: depth stencil and sampler support */
static const struct st_extension_format_mapping depthstencil_mapping[] = {
{ { o(ARB_depth_buffer_float) },
{ PIPE_FORMAT_Z32_FLOAT,
PIPE_FORMAT_Z32_FLOAT_S8X24_UINT } },
};
/* Required: sampler support */
static const struct st_extension_format_mapping texture_mapping[] = {
{ { o(ARB_texture_compression_rgtc) },
{ PIPE_FORMAT_RGTC1_UNORM,
PIPE_FORMAT_RGTC1_SNORM,
PIPE_FORMAT_RGTC2_UNORM,
PIPE_FORMAT_RGTC2_SNORM } },
{ { o(EXT_texture_compression_latc) },
{ PIPE_FORMAT_LATC1_UNORM,
PIPE_FORMAT_LATC1_SNORM,
PIPE_FORMAT_LATC2_UNORM,
PIPE_FORMAT_LATC2_SNORM } },
{ { o(EXT_texture_compression_s3tc),
891
o(ANGLE_texture_compression_dxt) },
892 893 894 895 896
{ PIPE_FORMAT_DXT1_RGB,
PIPE_FORMAT_DXT1_RGBA,
PIPE_FORMAT_DXT3_RGBA,
PIPE_FORMAT_DXT5_RGBA } },
897 898 899 900 901 902
{ { o(EXT_texture_compression_s3tc_srgb) },
{ PIPE_FORMAT_DXT1_SRGB,
PIPE_FORMAT_DXT1_SRGBA,
PIPE_FORMAT_DXT3_SRGBA,
PIPE_FORMAT_DXT5_SRGBA } },
903 904 905 906 907 908
{ { o(ARB_texture_compression_bptc) },
{ PIPE_FORMAT_BPTC_RGBA_UNORM,
PIPE_FORMAT_BPTC_SRGBA,
PIPE_FORMAT_BPTC_RGB_FLOAT,
PIPE_FORMAT_BPTC_RGB_UFLOAT } },
909 910 911 912
{ { o(TDFX_texture_compression_FXT1) },
{ PIPE_FORMAT_FXT1_RGB,
PIPE_FORMAT_FXT1_RGBA } },
913 914
{ { o(KHR_texture_compression_astc_ldr),
o(KHR_texture_compression_astc_sliced_3d) },
Ilia Mirkin's avatar
Ilia Mirkin committed
915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943
{ PIPE_FORMAT_ASTC_4x4,
PIPE_FORMAT_ASTC_5x4,
PIPE_FORMAT_ASTC_5x5,
PIPE_FORMAT_ASTC_6x5,
PIPE_FORMAT_ASTC_6x6,
PIPE_FORMAT_ASTC_8x5,
PIPE_FORMAT_ASTC_8x6,
PIPE_FORMAT_ASTC_8x8,
PIPE_FORMAT_ASTC_10x5,
PIPE_FORMAT_ASTC_10x6,
PIPE_FORMAT_ASTC_10x8,
PIPE_FORMAT_ASTC_10x10,
PIPE_FORMAT_ASTC_12x10,
PIPE_FORMAT_ASTC_12x12,
PIPE_FORMAT_ASTC_4x4_SRGB,
PIPE_FORMAT_ASTC_5x4_SRGB,
PIPE_FORMAT_ASTC_5x5_SRGB,
PIPE_FORMAT_ASTC_6x5_SRGB,
PIPE_FORMAT_ASTC_6x6_SRGB,
PIPE_FORMAT_ASTC_8x5_SRGB,
PIPE_FORMAT_ASTC_8x6_SRGB,
PIPE_FORMAT_ASTC_8x8_SRGB,
PIPE_FORMAT_ASTC_10x5_SRGB,
PIPE_FORMAT_ASTC_10x6_SRGB,
PIPE_FORMAT_ASTC_10x8_SRGB,
PIPE_FORMAT_ASTC_10x10_SRGB,
PIPE_FORMAT_ASTC_12x10_SRGB,
PIPE_FORMAT_ASTC_12x12_SRGB } },
944
/* ASTC software fallback support. */
945 946
{ { o(KHR_texture_compression_astc_ldr),
o(KHR_texture_compression_astc_sliced_3d) },
947 948 949
{ PIPE_FORMAT_R8G8B8A8_UNORM,
PIPE_FORMAT_R8G8B8A8_SRGB } },
950 951 952 953 954 955 956 957 958
{ { o(EXT_texture_shared_exponent) },
{ PIPE_FORMAT_R9G9B9E5_FLOAT } },
{ { o(EXT_texture_snorm) },
{ PIPE_FORMAT_R8G8B8A8_SNORM } },
{ { o(EXT_texture_sRGB),
o(EXT_texture_sRGB_decode) },
{ PIPE_FORMAT_A8B8G8R8_SRGB,
959 960 961
PIPE_FORMAT_B8G8R8A8_SRGB,
PIPE_FORMAT_A8R8G8B8_SRGB,
PIPE_FORMAT_R8G8B8A8_SRGB},
962 963
GL_TRUE }, /* at least one format must be supported */
964 965 966 967
{ { o(EXT_texture_sRGB_R8) },
{ PIPE_FORMAT_R8_SRGB },
GL_TRUE },
968 969 970 971 972
{ { o(EXT_texture_type_2_10_10_10_REV) },
{ PIPE_FORMAT_R10G10B10A2_UNORM,
PIPE_FORMAT_B10G10R10A2_UNORM },
GL_TRUE }, /* at least one format must be supported */
973 974 975 976 977 978 979 980 981
{ { o(ATI_texture_compression_3dc) },
{ PIPE_FORMAT_LATC2_UNORM } },
{ { o(MESA_ycbcr_texture) },
{ PIPE_FORMAT_UYVY,
PIPE_FORMAT_YUYV }, | __label__pos | 0.979322 |
Commits
Ivan Vučica committed a2a6c69
The Code™!
• Participants
• Parent commits 4cab604
• Branches master
Comments (0)
Files changed (17)
+xkcd #1110 for iOS
+==================
+
+Inspired by recent discussions on how long it could take Google to develop
+standalone Google Maps, I decided to prove my opinion that it should take very,
+very short time.
+
+So based on the idea from Florian Wesch - @dividuum - and using his tiles for
+Randall Munroe's xkcd comic #1110):
+ http://xkcd-map.rent-a-geek.de
+I've decided to develop a small app that would display just the "map" data.
+
+It took me around 3h.
+
+How long would it take Google to add basic search and routing to such a maps
+app? I estimate it should take them at most, in the worst case scenario, about
+3 months to be at the same stage as the pre-iOS 6 Maps app.
+
+Again, that's the worst case scenario, with Google's resources for hiring
+engineers.
+
+This app uses `CATiledLayer` and the fact that its `-drawInContext:` is
+multithreaded. This means we can even download the tiles during
+`-drawInContext:`. To be nicer to Florian's and user's bandwidth, there's also
+some caching of the downloaded images.
+
+View which contains the `CATiledLayer` subclass doesn't do anything except
+contain this special layer. `UIScrollView` does all the hard work of handling
+scrolling and zooming, which `CATiledLayer` happily picks up and orders drawing
+of its own contents.
+
+This is a universal app for iPhone and iPad. It was tested only in the
+simulator, and also seems to work fine on simulated iPhone 5.
+
+-- Ivan Vučica <[email protected]>
+
File XKCD1110.xcodeproj/project.pbxproj
7FF16E9E16175B7300F0251D /* IVMainViewController_iPhone.xib in Resources */ = {isa = PBXBuildFile; fileRef = 7FF16E9C16175B7300F0251D /* IVMainViewController_iPhone.xib */; };
7FF16EA116175B7300F0251D /* IVMainViewController_iPad.xib in Resources */ = {isa = PBXBuildFile; fileRef = 7FF16E9F16175B7300F0251D /* IVMainViewController_iPad.xib */; };
7FF16EA416175B7300F0251D /* IVFlipsideViewController.xib in Resources */ = {isa = PBXBuildFile; fileRef = 7FF16EA216175B7300F0251D /* IVFlipsideViewController.xib */; };
+ 7FF16EAC16175C6B00F0251D /* IVXkcdView.m in Sources */ = {isa = PBXBuildFile; fileRef = 7FF16EAB16175C6B00F0251D /* IVXkcdView.m */; };
+ 7FF16EAF16175CA900F0251D /* IVXkcdTiledLayer.m in Sources */ = {isa = PBXBuildFile; fileRef = 7FF16EAE16175CA900F0251D /* IVXkcdTiledLayer.m */; };
+ 7FF16EB116175EDF00F0251D /* QuartzCore.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 7FF16EB016175EDF00F0251D /* QuartzCore.framework */; };
+ 7FF16EB816176CDF00F0251D /* NSData+HNCaching.m in Sources */ = {isa = PBXBuildFile; fileRef = 7FF16EB316176CDF00F0251D /* NSData+HNCaching.m */; };
+ 7FF16EB916176CDF00F0251D /* NSURL+HNCaching.m in Sources */ = {isa = PBXBuildFile; fileRef = 7FF16EB516176CDF00F0251D /* NSURL+HNCaching.m */; };
+ 7FF16EBA16176CDF00F0251D /* UIImage+HNCaching.m in Sources */ = {isa = PBXBuildFile; fileRef = 7FF16EB716176CDF00F0251D /* UIImage+HNCaching.m */; };
/* End PBXBuildFile section */
/* Begin PBXFileReference section */
7FF16E9D16175B7300F0251D /* en */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = en; path = en.lproj/IVMainViewController_iPhone.xib; sourceTree = "<group>"; };
7FF16EA016175B7300F0251D /* en */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = en; path = en.lproj/IVMainViewController_iPad.xib; sourceTree = "<group>"; };
7FF16EA316175B7300F0251D /* en */ = {isa = PBXFileReference; lastKnownFileType = file.xib; name = en; path = en.lproj/IVFlipsideViewController.xib; sourceTree = "<group>"; };
+ 7FF16EAA16175C6B00F0251D /* IVXkcdView.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = IVXkcdView.h; sourceTree = "<group>"; };
+ 7FF16EAB16175C6B00F0251D /* IVXkcdView.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = IVXkcdView.m; sourceTree = "<group>"; };
+ 7FF16EAD16175CA900F0251D /* IVXkcdTiledLayer.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = IVXkcdTiledLayer.h; sourceTree = "<group>"; };
+ 7FF16EAE16175CA900F0251D /* IVXkcdTiledLayer.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = IVXkcdTiledLayer.m; sourceTree = "<group>"; };
+ 7FF16EB016175EDF00F0251D /* QuartzCore.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = QuartzCore.framework; path = System/Library/Frameworks/QuartzCore.framework; sourceTree = SDKROOT; };
+ 7FF16EB216176CDF00F0251D /* NSData+HNCaching.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSData+HNCaching.h"; sourceTree = "<group>"; };
+ 7FF16EB316176CDF00F0251D /* NSData+HNCaching.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSData+HNCaching.m"; sourceTree = "<group>"; };
+ 7FF16EB416176CDF00F0251D /* NSURL+HNCaching.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSURL+HNCaching.h"; sourceTree = "<group>"; };
+ 7FF16EB516176CDF00F0251D /* NSURL+HNCaching.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSURL+HNCaching.m"; sourceTree = "<group>"; };
+ 7FF16EB616176CDF00F0251D /* UIImage+HNCaching.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "UIImage+HNCaching.h"; sourceTree = "<group>"; };
+ 7FF16EB716176CDF00F0251D /* UIImage+HNCaching.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "UIImage+HNCaching.m"; sourceTree = "<group>"; };
/* End PBXFileReference section */
/* Begin PBXFrameworksBuildPhase section */
isa = PBXFrameworksBuildPhase;
buildActionMask = 2147483647;
files = (
+ 7FF16EB116175EDF00F0251D /* QuartzCore.framework in Frameworks */,
7FF16E7F16175B7100F0251D /* UIKit.framework in Frameworks */,
7FF16E8116175B7100F0251D /* Foundation.framework in Frameworks */,
7FF16E8316175B7100F0251D /* CoreGraphics.framework in Frameworks */,
7FF16E6F16175B7000F0251D = {
isa = PBXGroup;
children = (
+ 7FF16EB016175EDF00F0251D /* QuartzCore.framework */,
7FF16E8416175B7100F0251D /* XKCD1110 */,
7FF16E7D16175B7100F0251D /* Frameworks */,
7FF16E7B16175B7100F0251D /* Products */,
7FF16E9F16175B7300F0251D /* IVMainViewController_iPad.xib */,
7FF16EA216175B7300F0251D /* IVFlipsideViewController.xib */,
7FF16E8516175B7100F0251D /* Supporting Files */,
+ 7FF16EAA16175C6B00F0251D /* IVXkcdView.h */,
+ 7FF16EAB16175C6B00F0251D /* IVXkcdView.m */,
+ 7FF16EAD16175CA900F0251D /* IVXkcdTiledLayer.h */,
+ 7FF16EAE16175CA900F0251D /* IVXkcdTiledLayer.m */,
+ 7FF16EB216176CDF00F0251D /* NSData+HNCaching.h */,
+ 7FF16EB316176CDF00F0251D /* NSData+HNCaching.m */,
+ 7FF16EB416176CDF00F0251D /* NSURL+HNCaching.h */,
+ 7FF16EB516176CDF00F0251D /* NSURL+HNCaching.m */,
+ 7FF16EB616176CDF00F0251D /* UIImage+HNCaching.h */,
+ 7FF16EB716176CDF00F0251D /* UIImage+HNCaching.m */,
);
path = XKCD1110;
sourceTree = "<group>";
/* End PBXGroup section */
/* Begin PBXNativeTarget section */
- 7FF16E7916175B7100F0251D /* XKCD1110 */ = {
+ 7FF16E7916175B7100F0251D /* xkcd #1110 */ = {
isa = PBXNativeTarget;
- buildConfigurationList = 7FF16EA716175B7300F0251D /* Build configuration list for PBXNativeTarget "XKCD1110" */;
+ buildConfigurationList = 7FF16EA716175B7300F0251D /* Build configuration list for PBXNativeTarget "xkcd #1110" */;
buildPhases = (
7FF16E7616175B7100F0251D /* Sources */,
7FF16E7716175B7100F0251D /* Frameworks */,
);
dependencies = (
);
- name = XKCD1110;
+ name = "xkcd #1110";
productName = XKCD1110;
productReference = 7FF16E7A16175B7100F0251D /* XKCD1110.app */;
productType = "com.apple.product-type.application";
projectDirPath = "";
projectRoot = "";
targets = (
- 7FF16E7916175B7100F0251D /* XKCD1110 */,
+ 7FF16E7916175B7100F0251D /* xkcd #1110 */,
);
};
/* End PBXProject section */
7FF16E8F16175B7200F0251D /* IVAppDelegate.m in Sources */,
7FF16E9816175B7300F0251D /* IVMainViewController.m in Sources */,
7FF16E9B16175B7300F0251D /* IVFlipsideViewController.m in Sources */,
+ 7FF16EAC16175C6B00F0251D /* IVXkcdView.m in Sources */,
+ 7FF16EAF16175CA900F0251D /* IVXkcdTiledLayer.m in Sources */,
+ 7FF16EB816176CDF00F0251D /* NSData+HNCaching.m in Sources */,
+ 7FF16EB916176CDF00F0251D /* NSURL+HNCaching.m in Sources */,
+ 7FF16EBA16176CDF00F0251D /* UIImage+HNCaching.m in Sources */,
);
runOnlyForDeploymentPostprocessing = 0;
};
defaultConfigurationIsVisible = 0;
defaultConfigurationName = Release;
};
- 7FF16EA716175B7300F0251D /* Build configuration list for PBXNativeTarget "XKCD1110" */ = {
+ 7FF16EA716175B7300F0251D /* Build configuration list for PBXNativeTarget "xkcd #1110" */ = {
isa = XCConfigurationList;
buildConfigurations = (
7FF16EA816175B7300F0251D /* Debug */,
File XKCD1110/IVMainViewController.h
#import "IVFlipsideViewController.h"
-@interface IVMainViewController : UIViewController <IVFlipsideViewControllerDelegate>
+@class IVXkcdView;
+
+@interface IVMainViewController : UIViewController <IVFlipsideViewControllerDelegate, UIScrollViewDelegate>
@property (strong, nonatomic) UIPopoverController *flipsidePopoverController;
- (IBAction)showInfo:(id)sender;
+@property (retain, nonatomic) IBOutlet UILabel *statusLabel;
+@property (retain, nonatomic) IBOutlet UIScrollView *scrollView;
+@property (retain, nonatomic) IBOutlet IVXkcdView *xkcdView;
+
@end
File XKCD1110/IVMainViewController.m
//
#import "IVMainViewController.h"
+#import "IVXkcdView.h"
@interface IVMainViewController ()
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
+ [self.scrollView zoomToRect:CGRectMake(0, 0, 256, 256) animated:NO];
+ [self performSelector:@selector(initialZoom) withObject:nil afterDelay:0.5];
+ self.title = @"xkcd #1110";
+}
+
+- (void)initialZoom
+{
+ [UIView beginAnimations:@"initialZoom" context:nil];
+ [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
+ [UIView setAnimationDuration:5];
+ [self.scrollView zoomToRect:CGRectFromString(@"{{127.928, 127.082}, {0.498523, 0.623154}}") animated:NO];
+ [UIView commitAnimations];
}
- (void)didReceiveMemoryWarning
- (void)dealloc
{
[_flipsidePopoverController release];
+ [_xkcdView release];
+ [_scrollView release];
+ [_statusLabel release];
[super dealloc];
}
}
}
+#pragma mark - Scrollview delegate
+- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
+{
+ return self.xkcdView;
+}
+
+- (void)scrollViewDidScroll:(UIScrollView *)scrollView
+{
+ [self updateStatus];
+}
+
+- (void)scrollViewDidZoom:(UIScrollView *)scrollView
+{
+ [self updateStatus];
+}
+
+- (void)updateStatus
+{
+ NSString * status = [NSString stringWithFormat:@"Scale: %g", self.scrollView.zoomScale];
+ self.statusLabel.text = status;
+
+ CGRect visibleRect = {0};
+
+ visibleRect.origin = self.scrollView.contentOffset;
+ visibleRect.origin.x /= self.scrollView.zoomScale;
+ visibleRect.origin.y /= self.scrollView.zoomScale;
+
+ visibleRect.size = self.scrollView.bounds.size;
+ visibleRect.size.width /= self.scrollView.zoomScale;
+ visibleRect.size.height /= self.scrollView.zoomScale;
+
+ //NSLog(@"Visible %@", NSStringFromCGRect(visibleRect));
+
+}
@end
File XKCD1110/IVXkcdTiledLayer.h
+//
+// IVXkcdTiledLayer.h
+// XKCD1110
+//
+// Created by Ivan Vučica on 29.9.2012..
+// Copyright (c) 2012. Ivan Vučica. All rights reserved.
+//
+
+#import <QuartzCore/QuartzCore.h>
+
+@interface IVXkcdTiledLayer : CATiledLayer
+
+@end
File XKCD1110/IVXkcdTiledLayer.m
+//
+// IVXkcdTiledLayer.m
+// XKCD1110
+//
+// Created by Ivan Vučica on 29.9.2012..
+// Copyright (c) 2012. Ivan Vučica. All rights reserved.
+//
+
+#import "IVXkcdTiledLayer.h"
+#import "UIImage+HNCaching.h"
+
+#define ZOOM_SUPPORT 1
+
+@implementation IVXkcdTiledLayer
+
+- (void)drawInContext:(CGContextRef)context
+{
+ // Fetch clip box in *world* space; context's CTM is preconfigured for world space->tile pixel space transform
+ CGRect box = CGContextGetClipBoundingBox(context);
+
+ // Calculate tile index
+ CGFloat contentsScale = [self respondsToSelector:@selector(contentsScale)]?[self contentsScale]:1.0;
+ CGSize tileSize = [(CATiledLayer*)self tileSize];
+ CGFloat scaling = box.size.width / tileSize.width;
+#if !(ZOOM_SUPPORT)
+ CGFloat x = box.origin.x * contentsScale / tileSize.width;
+ CGFloat y = box.origin.y * contentsScale / tileSize.height;
+#else
+ CGRect tbox = CGRectApplyAffineTransform(CGRectMake(0, 0, tileSize.width, tileSize.height),
+ CGAffineTransformInvert(CGContextGetCTM(context)));
+ CGFloat x = box.origin.x / tbox.size.width;
+ CGFloat y = box.origin.y / tbox.size.height;
+#endif
+ CGPoint tile = CGPointMake(x, y);
+
+ // Clear background
+ CGContextSetFillColorWithColor(context, [[UIColor grayColor] CGColor]);
+ CGContextFillRect(context, box);
+
+ // Rendering the contents
+ CGContextSaveGState(context);
+ CGContextConcatCTM(context, [self transformForTile:tile]);
+
+ UIImage * img = [self imageForTile:tile atZoomLevel:-log(scaling)/log(2)];
+ CGContextTranslateCTM(context, 0, box.size.height);
+ CGContextScaleCTM(context, 1, -1);
+ CGContextDrawImage(context, CGContextGetClipBoundingBox(context), [img CGImage]);
+
+ CGContextRestoreGState(context);
+
+#if 0
+ // Render label (Setup)
+ UIFont* font = [UIFont fontWithName:@"CourierNewPS-BoldMT" size:12 * scaling * 2];
+ CGContextSelectFont(context, [[font fontName] cStringUsingEncoding:NSASCIIStringEncoding], [font pointSize], kCGEncodingMacRoman);
+ CGContextSetTextDrawingMode(context, kCGTextFill);
+ CGContextSetTextMatrix(context, CGAffineTransformMakeScale(1, -1));
+ CGContextSetFillColorWithColor(context, [[UIColor greenColor] CGColor]);
+
+ // Draw label
+ NSString* s = [NSString stringWithFormat:@"(%.1f, %.1f) %g",x,y,log(scaling)/log(2)];
+ CGContextShowTextAtPoint(context,
+ box.origin.x,
+ box.origin.y + [font pointSize],
+ [s cStringUsingEncoding:NSMacOSRomanStringEncoding],
+ [s lengthOfBytesUsingEncoding:NSMacOSRomanStringEncoding]);
+#endif
+}
+
+- (CGAffineTransform)transformForTile:(CGPoint)tile
+{
+ return CGAffineTransformIdentity;
+}
+
+- (UIImage*)imageForTile:(CGPoint)tile atZoomLevel:(int)zoomLevel
+{
+ NSString * urlString = [NSString stringWithFormat:@"http://xkcd1.rent-a-geek.de/converted/%d-%d-%d.png", zoomLevel, (int)tile.x, (int)tile.y];
+ NSURL * url = [NSURL URLWithString:urlString];
+
+ return [UIImage imageWithContentsOfURLAndCaching:url];
+}
+
+@end
File XKCD1110/IVXkcdView.h
+//
+// IVXkcdView.h
+// XKCD1110
+//
+// Created by Ivan Vučica on 29.9.2012..
+// Copyright (c) 2012. Ivan Vučica. All rights reserved.
+//
+
+#import <UIKit/UIKit.h>
+
+@interface IVXkcdView : UIView
+
+@end
File XKCD1110/IVXkcdView.m
+//
+// IVXkcdView.m
+// XKCD1110
+//
+// Created by Ivan Vučica on 29.9.2012..
+// Copyright (c) 2012. Ivan Vučica. All rights reserved.
+//
+
+#import "IVXkcdView.h"
+#import <QuartzCore/QuartzCore.h>
+#import "IVXkcdTiledLayer.h"
+
+@implementation IVXkcdView
+
++ (Class)layerClass
+{
+ return [IVXkcdTiledLayer class];
+}
+
+- (id)initWithFrame:(CGRect)frame
+{
+ self = [super initWithFrame:frame];
+ if (self) {
+ // Initialization code
+ CATiledLayer *tempTiledLayer = (CATiledLayer*)self.layer;
+
+ tempTiledLayer.levelsOfDetail = 10;
+
+ tempTiledLayer.levelsOfDetailBias = 10;
+
+
+ }
+ return self;
+}
+- (id)initWithCoder:(NSCoder *)aDecoder
+{
+ self = [super initWithCoder:aDecoder];
+ if(!self)
+ return nil;
+ CATiledLayer *tempTiledLayer = (CATiledLayer*)self.layer;
+
+ tempTiledLayer.levelsOfDetail = 11;
+
+ tempTiledLayer.levelsOfDetailBias = 10;
+
+
+ return self;
+}
+/*
+- (void)didMoveToSuperview
+{
+ // superview.maximumZoomScale returns 0 even here, despite superview being a scrollview :/
+
+ CATiledLayer *tempTiledLayer = (CATiledLayer*)self.layer;
+
+ tempTiledLayer.levelsOfDetail = ((UIScrollView*)self.superview).maximumZoomScale;
+
+ tempTiledLayer.levelsOfDetailBias = ((UIScrollView*)self.superview).maximumZoomScale-1;
+
+ NSLog(@"LOD in superview %@: %d", self.superview, tempTiledLayer.levelsOfDetail);
+
+ [tempTiledLayer setNeedsDisplay];
+
+}
+ */
+/*
+- (void)drawRect:(CGRect)rect
+{
+ // Drawing code
+
+ CGContextRef context = UIGraphicsGetCurrentContext();
+
+}
+*/
+
+- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
+{
+ [super touchesBegan:touches withEvent:event];
+ NSLog(@"Touchesbegan %d", touches.count);
+}
+@end
File XKCD1110/NSData+HNCaching.h
+//
+// NSData+HNCaching.h
+// HN
+//
+// Created by Ivan Vučica on 24.8.2012..
+// Copyright (c) 2012. Hindarium. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+
+@interface NSData (HNCaching)
++ (NSData*) dataWithContentsOfURLAndCaching: (NSURL*)url;
+@end
File XKCD1110/NSData+HNCaching.m
+//
+// NSData+HNCaching.m
+// HN
+//
+// Created by Ivan Vučica on 24.8.2012..
+// Copyright (c) 2012. Hindarium. All rights reserved.
+//
+
+#import "NSData+HNCaching.h"
+#import "NSURL+HNCaching.h"
+//#import "ActivityManager.h"
+
+@implementation NSData (HNCaching)
++ (NSData*) dataWithContentsOfURLAndCaching: (NSURL*)url
+{
+ NSData * data;
+
+ if(![url cacheValid])
+ {
+ //[[ActivityManager sharedManager] addActivity];
+ data = [NSData dataWithContentsOfURL: url];
+ //[[ActivityManager sharedManager] removeActivity];
+ if(data)
+ {
+ [data writeToFile: [url cacheFile] atomically: YES];
+ return data;
+ }
+ }
+
+ return [self dataWithContentsOfFile: [url cacheFile]];
+}
+
+
+@end
File XKCD1110/NSURL+HNCaching.h
+//
+// NSURL+HNCaching.h
+// HN
+//
+// Created by Ivan Vučica on 3.7.2012..
+// Copyright (c) 2012. Hindarium. All rights reserved.
+//
+
+#import <Foundation/Foundation.h>
+
+@interface NSURL (HNCaching)
+-(NSString*)cacheFile;
+-(BOOL)cacheExists;
+-(BOOL)cacheValid;
+-(void)cacheDestroy;
+@end
File XKCD1110/NSURL+HNCaching.m
+//
+// NSURL+HNCaching.m
+// HN
+//
+// Created by Ivan Vučica on 3.7.2012..
+// Copyright (c) 2012. Hindarium. All rights reserved.
+//
+
+#import "NSURL+HNCaching.h"
+
+@implementation NSURL (HNCaching)
+
+-(NSString*)cacheFile
+{
+ NSString * cacheFile = [[[[self absoluteString] stringByDeletingLastPathComponent] lastPathComponent] stringByAppendingString: [[self absoluteString] lastPathComponent]];
+ NSString * cachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
+ return [cachePath stringByAppendingPathComponent:cacheFile];
+}
+
+#if 1
+#define CACHE_TIME 30*60 // 30min
+#else
+#define CACHE_TIME 5 // 5 sec
+#warning Cache time set to 5 sec!
+#endif
+- (BOOL)cacheExists
+{
+ return [[NSFileManager defaultManager] fileExistsAtPath:[self cacheFile]];
+}
+- (BOOL)cacheValid
+{
+ return [self cacheExists] &&
+ [[[[NSFileManager defaultManager] attributesOfItemAtPath:[self cacheFile] error:nil] valueForKey:NSFileModificationDate] timeIntervalSinceNow] > -CACHE_TIME;
+}
+
+- (void)cacheDestroy
+{
+ [[NSFileManager defaultManager] removeItemAtPath:[self cacheFile] error:nil];
+}
+@end
File XKCD1110/UIImage+HNCaching.h
+//
+// UIImage+HNCaching.h
+// HN
+//
+// Created by Ivan Vučica on 10.7.2012..
+// Copyright (c) 2012. Hindarium. All rights reserved.
+//
+
+#import <UIKit/UIKit.h>
+
+@interface UIImage (HNCaching)
++ (UIImage*) imageWithContentsOfURLAndCaching: (NSURL*)url;
+@end
File XKCD1110/UIImage+HNCaching.m
+//
+// UIImage+HNCaching.m
+// HN
+//
+// Created by Ivan Vučica on 10.7.2012..
+// Copyright (c) 2012. Hindarium. All rights reserved.
+//
+
+#import "UIImage+HNCaching.h"
+//#import "ActivityManager.h"
+#import "NSURL+HNCaching.h"
+
+@implementation UIImage (HNCaching)
++ (UIImage*) imageWithContentsOfURLAndCaching: (NSURL*)url
+{
+
+ NSData * data;
+
+ if(![url cacheValid])
+ {
+ //[[ActivityManager sharedManager] addActivity];
+ data = [NSData dataWithContentsOfURL: url];
+ //[[ActivityManager sharedManager] removeActivity];
+ if(data)
+ {
+ UIImage * img = [self imageWithData:data];
+ if(img)
+ {
+ [data writeToFile: [url cacheFile] atomically: YES];
+ return img;
+ }
+ }
+ }
+
+ return [self imageWithContentsOfFile: [url cacheFile]];
+}
+
+@end
File XKCD1110/en.lproj/IVFlipsideViewController.xib
<archive type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="8.00">
<data>
<int key="IBDocument.SystemTarget">1536</int>
- <string key="IBDocument.SystemVersion">12A269</string>
- <string key="IBDocument.InterfaceBuilderVersion">2835</string>
- <string key="IBDocument.AppKitVersion">1187</string>
- <string key="IBDocument.HIToolboxVersion">624.00</string>
+ <string key="IBDocument.SystemVersion">12C54</string>
+ <string key="IBDocument.InterfaceBuilderVersion">2840</string>
+ <string key="IBDocument.AppKitVersion">1187.34</string>
+ <string key="IBDocument.HIToolboxVersion">625.00</string>
<object class="NSMutableDictionary" key="IBDocument.PluginVersions">
<string key="NS.key.0">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
- <string key="NS.object.0">1919</string>
+ <string key="NS.object.0">1926</string>
</object>
<array key="IBDocument.IntegratedClassDependencies">
<string>IBNSLayoutConstraint</string>
<string>IBProxyObject</string>
<string>IBUIBarButtonItem</string>
+ <string>IBUILabel</string>
<string>IBUINavigationBar</string>
<string>IBUINavigationItem</string>
<string>IBUIView</string>
<int key="NSvFlags">290</int>
<string key="NSFrameSize">{320, 44}</string>
<reference key="NSSuperview" ref="249263867"/>
- <reference key="NSWindow"/>
- <reference key="NSNextKeyView"/>
+ <reference key="NSNextKeyView" ref="585174927"/>
<bool key="IBUIOpaque">NO</bool>
<bool key="IBUIClearsContextBeforeDrawing">NO</bool>
<string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>
<array key="IBUIItems">
<object class="IBUINavigationItem" id="553200710">
<reference key="IBUINavigationBar" ref="871675769"/>
- <string key="IBUITitle">Title</string>
+ <string key="IBUITitle">Info</string>
<object class="IBUIBarButtonItem" key="IBUILeftBarButtonItem" id="854562692">
<string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>
<int key="IBUIStyle">1</int>
</object>
</array>
</object>
+ <object class="IBUILabel" id="585174927">
+ <reference key="NSNextResponder" ref="249263867"/>
+ <int key="NSvFlags">292</int>
+ <string key="NSFrame">{{20, 93}, {281, 34}}</string>
+ <reference key="NSSuperview" ref="249263867"/>
+ <reference key="NSNextKeyView" ref="858711408"/>
+ <string key="NSReuseIdentifierKey">_NS:9</string>
+ <bool key="IBUIOpaque">NO</bool>
+ <bool key="IBUIClipsSubviews">YES</bool>
+ <int key="IBUIContentMode">7</int>
+ <bool key="IBUIUserInteractionEnabled">NO</bool>
+ <string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>
+ <string key="IBUIText">xkcd #1110</string>
+ <object class="NSColor" key="IBUITextColor" id="353423499">
+ <int key="NSColorSpace">3</int>
+ <bytes key="NSWhite">MQA</bytes>
+ </object>
+ <nil key="IBUIHighlightedColor"/>
+ <int key="IBUIBaselineAdjustment">0</int>
+ <int key="IBUITextAlignment">1</int>
+ <object class="IBUIFontDescription" key="IBUIFontDescription">
+ <int key="type">2</int>
+ <double key="pointSize">28</double>
+ </object>
+ <object class="NSFont" key="IBUIFont">
+ <string key="NSName">Helvetica-Bold</string>
+ <double key="NSSize">28</double>
+ <int key="NSfFlags">16</int>
+ </object>
+ <bool key="IBUIAdjustsFontSizeToFit">NO</bool>
+ </object>
+ <object class="IBUILabel" id="858711408">
+ <reference key="NSNextResponder" ref="249263867"/>
+ <int key="NSvFlags">292</int>
+ <string key="NSFrame">{{20, 126}, {281, 34}}</string>
+ <reference key="NSSuperview" ref="249263867"/>
+ <reference key="NSNextKeyView" ref="538246754"/>
+ <string key="NSReuseIdentifierKey">_NS:9</string>
+ <bool key="IBUIOpaque">NO</bool>
+ <bool key="IBUIClipsSubviews">YES</bool>
+ <int key="IBUIContentMode">7</int>
+ <bool key="IBUIUserInteractionEnabled">NO</bool>
+ <string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>
+ <string key="IBUIText">for iOS</string>
+ <reference key="IBUITextColor" ref="353423499"/>
+ <nil key="IBUIHighlightedColor"/>
+ <int key="IBUIBaselineAdjustment">0</int>
+ <int key="IBUITextAlignment">1</int>
+ <object class="IBUIFontDescription" key="IBUIFontDescription" id="577310509">
+ <int key="type">1</int>
+ <double key="pointSize">14</double>
+ </object>
+ <object class="NSFont" key="IBUIFont" id="379834064">
+ <string key="NSName">Helvetica</string>
+ <double key="NSSize">14</double>
+ <int key="NSfFlags">16</int>
+ </object>
+ <bool key="IBUIAdjustsFontSizeToFit">NO</bool>
+ </object>
+ <object class="IBUILabel" id="399235240">
+ <reference key="NSNextResponder" ref="249263867"/>
+ <int key="NSvFlags">292</int>
+ <string key="NSFrame">{{20, 219}, {281, 34}}</string>
+ <reference key="NSSuperview" ref="249263867"/>
+ <reference key="NSNextKeyView" ref="262554441"/>
+ <string key="NSReuseIdentifierKey">_NS:9</string>
+ <bool key="IBUIOpaque">NO</bool>
+ <bool key="IBUIClipsSubviews">YES</bool>
+ <int key="IBUIContentMode">7</int>
+ <bool key="IBUIUserInteractionEnabled">NO</bool>
+ <string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>
+ <string key="IBUIText">Artwork: Randall Munroe</string>
+ <reference key="IBUITextColor" ref="353423499"/>
+ <nil key="IBUIHighlightedColor"/>
+ <int key="IBUIBaselineAdjustment">0</int>
+ <int key="IBUITextAlignment">1</int>
+ <reference key="IBUIFontDescription" ref="577310509"/>
+ <reference key="IBUIFont" ref="379834064"/>
+ <bool key="IBUIAdjustsFontSizeToFit">NO</bool>
+ </object>
+ <object class="IBUILabel" id="262554441">
+ <reference key="NSNextResponder" ref="249263867"/>
+ <int key="NSvFlags">292</int>
+ <string key="NSFrame">{{20, 244}, {281, 34}}</string>
+ <reference key="NSSuperview" ref="249263867"/>
+ <reference key="NSNextKeyView" ref="801664589"/>
+ <string key="NSReuseIdentifierKey">_NS:9</string>
+ <bool key="IBUIOpaque">NO</bool>
+ <bool key="IBUIClipsSubviews">YES</bool>
+ <int key="IBUIContentMode">7</int>
+ <bool key="IBUIUserInteractionEnabled">NO</bool>
+ <string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>
+ <string key="IBUIText">Slicing, web version and idea: Florian Wesch</string>
+ <reference key="IBUITextColor" ref="353423499"/>
+ <nil key="IBUIHighlightedColor"/>
+ <int key="IBUIBaselineAdjustment">0</int>
+ <int key="IBUITextAlignment">1</int>
+ <reference key="IBUIFontDescription" ref="577310509"/>
+ <reference key="IBUIFont" ref="379834064"/>
+ <bool key="IBUIAdjustsFontSizeToFit">NO</bool>
+ </object>
+ <object class="IBUILabel" id="801664589">
+ <reference key="NSNextResponder" ref="249263867"/>
+ <int key="NSvFlags">292</int>
+ <string key="NSFrame">{{20, 276}, {281, 34}}</string>
+ <reference key="NSSuperview" ref="249263867"/>
+ <reference key="NSNextKeyView" ref="144899368"/>
+ <string key="NSReuseIdentifierKey">_NS:9</string>
+ <bool key="IBUIOpaque">NO</bool>
+ <bool key="IBUIClipsSubviews">YES</bool>
+ <int key="IBUIContentMode">7</int>
+ <bool key="IBUIUserInteractionEnabled">NO</bool>
+ <string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>
+ <string key="IBUIText">iOS app: Ivan Vučica</string>
+ <reference key="IBUITextColor" ref="353423499"/>
+ <nil key="IBUIHighlightedColor"/>
+ <int key="IBUIBaselineAdjustment">0</int>
+ <int key="IBUITextAlignment">1</int>
+ <reference key="IBUIFontDescription" ref="577310509"/>
+ <reference key="IBUIFont" ref="379834064"/>
+ <bool key="IBUIAdjustsFontSizeToFit">NO</bool>
+ </object>
+ <object class="IBUILabel" id="144899368">
+ <reference key="NSNextResponder" ref="249263867"/>
+ <int key="NSvFlags">292</int>
+ <string key="NSFrame">{{20, 494}, {281, 34}}</string>
+ <reference key="NSSuperview" ref="249263867"/>
+ <reference key="NSNextKeyView"/>
+ <string key="NSReuseIdentifierKey">_NS:9</string>
+ <bool key="IBUIOpaque">NO</bool>
+ <bool key="IBUIClipsSubviews">YES</bool>
+ <int key="IBUIContentMode">7</int>
+ <bool key="IBUIUserInteractionEnabled">NO</bool>
+ <string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>
+ <string key="IBUIText">September 29, 2012</string>
+ <reference key="IBUITextColor" ref="353423499"/>
+ <nil key="IBUIHighlightedColor"/>
+ <int key="IBUIBaselineAdjustment">0</int>
+ <int key="IBUITextAlignment">1</int>
+ <reference key="IBUIFontDescription" ref="577310509"/>
+ <reference key="IBUIFont" ref="379834064"/>
+ <bool key="IBUIAdjustsFontSizeToFit">NO</bool>
+ </object>
+ <object class="IBUILabel" id="538246754">
+ <reference key="NSNextResponder" ref="249263867"/>
+ <int key="NSvFlags">292</int>
+ <string key="NSFrame">{{20, 177}, {281, 34}}</string>
+ <reference key="NSSuperview" ref="249263867"/>
+ <reference key="NSNextKeyView" ref="399235240"/>
+ <string key="NSReuseIdentifierKey">_NS:9</string>
+ <bool key="IBUIOpaque">NO</bool>
+ <bool key="IBUIClipsSubviews">YES</bool>
+ <int key="IBUIContentMode">7</int>
+ <bool key="IBUIUserInteractionEnabled">NO</bool>
+ <string key="targetRuntimeIdentifier">IBCocoaTouchFramework</string>
+ <string type="base64-UTF8" key="IBUIText">QWJvdXQgM2ggb2Ygd29yaywKb24gYSBjb2xkIFNlcHRlbWJlciBuaWdodC4</string>
+ <reference key="IBUITextColor" ref="353423499"/>
+ <nil key="IBUIHighlightedColor"/>
+ <int key="IBUIBaselineAdjustment">0</int>
+ <int key="IBUINumberOfLines">2</int>
+ <int key="IBUITextAlignment">1</int>
+ <reference key="IBUIFontDescription" ref="577310509"/>
+ <reference key="IBUIFont" ref="379834064"/>
+ <bool key="IBUIAdjustsFontSizeToFit">NO</bool>
+ <double key="preferredMaxLayoutWidth">281</double>
+ </object>
</array>
<string key="NSFrame">{{0, 20}, {320, 548}}</string>
<reference key="NSSuperview"/>
- <reference key="NSWindow"/>
<reference key="NSNextKeyView" ref="871675769"/>
<object class="NSColor" key="IBUIBackgroundColor">
<int key="NSColorSpace">3</int>
<reference key="object" ref="249263867"/>
<array class="NSMutableArray" key="children">
<reference ref="871675769"/>
+ <object class="IBNSLayoutConstraint" id="392172463">
+ <reference key="firstItem" ref="249263867"/>
+ <int key="firstAttribute">4</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="144899368"/>
+ <int key="secondAttribute">4</int>
+ <float key="multiplier">1</float>
+ <object class="IBNSLayoutSymbolicConstant" key="constant">
+ <double key="value">20</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">8</int>
+ <float key="scoringTypeFloat">29</float>
+ <int key="contentType">3</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="202359554">
+ <reference key="firstItem" ref="144899368"/>
+ <int key="firstAttribute">5</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="249263867"/>
+ <int key="secondAttribute">5</int>
+ <float key="multiplier">1</float>
+ <object class="IBNSLayoutSymbolicConstant" key="constant">
+ <double key="value">20</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">8</int>
+ <float key="scoringTypeFloat">29</float>
+ <int key="contentType">3</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="154419028">
+ <reference key="firstItem" ref="144899368"/>
+ <int key="firstAttribute">6</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="801664589"/>
+ <int key="secondAttribute">6</int>
+ <float key="multiplier">1</float>
+ <object class="IBLayoutConstant" key="constant">
+ <double key="value">0.0</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">6</int>
+ <float key="scoringTypeFloat">24</float>
+ <int key="contentType">2</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="534252093">
+ <reference key="firstItem" ref="249263867"/>
+ <int key="firstAttribute">4</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="801664589"/>
+ <int key="secondAttribute">4</int>
+ <float key="multiplier">1</float>
+ <object class="IBLayoutConstant" key="constant">
+ <double key="value">238</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">3</int>
+ <float key="scoringTypeFloat">9</float>
+ <int key="contentType">3</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="1013546937">
+ <reference key="firstItem" ref="801664589"/>
+ <int key="firstAttribute">6</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="262554441"/>
+ <int key="secondAttribute">6</int>
+ <float key="multiplier">1</float>
+ <object class="IBLayoutConstant" key="constant">
+ <double key="value">0.0</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">6</int>
+ <float key="scoringTypeFloat">24</float>
+ <int key="contentType">2</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="874739352">
+ <reference key="firstItem" ref="801664589"/>
+ <int key="firstAttribute">5</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="249263867"/>
+ <int key="secondAttribute">5</int>
+ <float key="multiplier">1</float>
+ <object class="IBNSLayoutSymbolicConstant" key="constant">
+ <double key="value">20</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">8</int>
+ <float key="scoringTypeFloat">29</float>
+ <int key="contentType">3</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="154836529">
+ <reference key="firstItem" ref="262554441"/>
+ <int key="firstAttribute">5</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="249263867"/>
+ <int key="secondAttribute">5</int>
+ <float key="multiplier">1</float>
+ <object class="IBNSLayoutSymbolicConstant" key="constant">
+ <double key="value">20</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">8</int>
+ <float key="scoringTypeFloat">29</float>
+ <int key="contentType">3</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="289565424">
+ <reference key="firstItem" ref="262554441"/>
+ <int key="firstAttribute">3</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="249263867"/>
+ <int key="secondAttribute">3</int>
+ <float key="multiplier">1</float>
+ <object class="IBLayoutConstant" key="constant">
+ <double key="value">244</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">3</int>
+ <float key="scoringTypeFloat">9</float>
+ <int key="contentType">3</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="945968116">
+ <reference key="firstItem" ref="262554441"/>
+ <int key="firstAttribute">6</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="399235240"/>
+ <int key="secondAttribute">6</int>
+ <float key="multiplier">1</float>
+ <object class="IBLayoutConstant" key="constant">
+ <double key="value">0.0</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">6</int>
+ <float key="scoringTypeFloat">24</float>
+ <int key="contentType">2</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="458947079">
+ <reference key="firstItem" ref="399235240"/>
+ <int key="firstAttribute">6</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="538246754"/>
+ <int key="secondAttribute">6</int>
+ <float key="multiplier">1</float>
+ <object class="IBLayoutConstant" key="constant">
+ <double key="value">0.0</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">6</int>
+ <float key="scoringTypeFloat">24</float>
+ <int key="contentType">2</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="534867620">
+ <reference key="firstItem" ref="399235240"/>
+ <int key="firstAttribute">5</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="249263867"/>
+ <int key="secondAttribute">5</int>
+ <float key="multiplier">1</float>
+ <object class="IBNSLayoutSymbolicConstant" key="constant">
+ <double key="value">20</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">8</int>
+ <float key="scoringTypeFloat">29</float>
+ <int key="contentType">3</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="967572429">
+ <reference key="firstItem" ref="399235240"/>
+ <int key="firstAttribute">3</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="538246754"/>
+ <int key="secondAttribute">4</int>
+ <float key="multiplier">1</float>
+ <object class="IBNSLayoutSymbolicConstant" key="constant">
+ <double key="value">8</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">6</int>
+ <float key="scoringTypeFloat">24</float>
+ <int key="contentType">3</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="30504726">
+ <reference key="firstItem" ref="538246754"/>
+ <int key="firstAttribute">5</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="249263867"/>
+ <int key="secondAttribute">5</int>
+ <float key="multiplier">1</float>
+ <object class="IBNSLayoutSymbolicConstant" key="constant">
+ <double key="value">20</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">8</int>
+ <float key="scoringTypeFloat">29</float>
+ <int key="contentType">3</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="506804384">
+ <reference key="firstItem" ref="538246754"/>
+ <int key="firstAttribute">3</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="249263867"/>
+ <int key="secondAttribute">3</int>
+ <float key="multiplier">1</float>
+ <object class="IBLayoutConstant" key="constant">
+ <double key="value">177</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">3</int>
+ <float key="scoringTypeFloat">9</float>
+ <int key="contentType">3</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="549522802">
+ <reference key="firstItem" ref="538246754"/>
+ <int key="firstAttribute">6</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="858711408"/>
+ <int key="secondAttribute">6</int>
+ <float key="multiplier">1</float>
+ <object class="IBLayoutConstant" key="constant">
+ <double key="value">0.0</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">6</int>
+ <float key="scoringTypeFloat">24</float>
+ <int key="contentType">2</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="294112825">
+ <reference key="firstItem" ref="858711408"/>
+ <int key="firstAttribute">5</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="249263867"/>
+ <int key="secondAttribute">5</int>
+ <float key="multiplier">1</float>
+ <object class="IBNSLayoutSymbolicConstant" key="constant">
+ <double key="value">20</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">8</int>
+ <float key="scoringTypeFloat">29</float>
+ <int key="contentType">3</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="236413759">
+ <reference key="firstItem" ref="858711408"/>
+ <int key="firstAttribute">6</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="585174927"/>
+ <int key="secondAttribute">6</int>
+ <float key="multiplier">1</float>
+ <object class="IBLayoutConstant" key="constant">
+ <double key="value">0.0</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">6</int>
+ <float key="scoringTypeFloat">24</float>
+ <int key="contentType">2</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="185966605">
+ <reference key="firstItem" ref="858711408"/>
+ <int key="firstAttribute">3</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="249263867"/>
+ <int key="secondAttribute">3</int>
+ <float key="multiplier">1</float>
+ <object class="IBLayoutConstant" key="constant">
+ <double key="value">126</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">3</int>
+ <float key="scoringTypeFloat">9</float>
+ <int key="contentType">3</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="746744863">
+ <reference key="firstItem" ref="585174927"/>
+ <int key="firstAttribute">5</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="249263867"/>
+ <int key="secondAttribute">5</int>
+ <float key="multiplier">1</float>
+ <object class="IBNSLayoutSymbolicConstant" key="constant">
+ <double key="value">20</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">8</int>
+ <float key="scoringTypeFloat">29</float>
+ <int key="contentType">3</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="873302976">
+ <reference key="firstItem" ref="585174927"/>
+ <int key="firstAttribute">3</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="249263867"/>
+ <int key="secondAttribute">3</int>
+ <float key="multiplier">1</float>
+ <object class="IBLayoutConstant" key="constant">
+ <double key="value">93</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">3</int>
+ <float key="scoringTypeFloat">9</float>
+ <int key="contentType">3</int>
+ </object>
+ <object class="IBNSLayoutConstraint" id="833081181">
+ <reference key="firstItem" ref="585174927"/>
+ <int key="firstAttribute">9</int>
+ <int key="relation">0</int>
+ <reference key="secondItem" ref="871675769"/>
+ <int key="secondAttribute">9</int>
+ <float key="multiplier">1</float>
+ <object class="IBLayoutConstant" key="constant">
+ <double key="value">0.0</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="249263867"/>
+ <int key="scoringType">6</int>
+ <float key="scoringTypeFloat">24</float>
+ <int key="contentType">2</int>
+ </object>
<object class="IBNSLayoutConstraint" id="591162250">
<reference key="firstItem" ref="871675769"/>
<int key="firstAttribute">6</int>
<float key="scoringTypeFloat">29</float>
<int key="contentType">3</int>
</object>
+ <reference ref="585174927"/>
+ <reference ref="858711408"/>
+ <reference ref="538246754"/>
+ <reference ref="399235240"/>
+ <reference ref="262554441"/>
+ <reference ref="801664589"/>
+ <reference ref="144899368"/>
</array>
<reference key="parent" ref="0"/>
</object>
<reference key="object" ref="591162250"/>
<reference key="parent" ref="249263867"/>
</object>
+ <object class="IBObjectRecord">
+ <int key="objectID">50</int>
+ <reference key="object" ref="585174927"/>
+ <array class="NSMutableArray" key="children"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">52</int>
+ <reference key="object" ref="833081181"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">55</int>
+ <reference key="object" ref="873302976"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">56</int>
+ <reference key="object" ref="858711408"/>
+ <array class="NSMutableArray" key="children">
+ <object class="IBNSLayoutConstraint" id="708718284">
+ <reference key="firstItem" ref="858711408"/>
+ <int key="firstAttribute">8</int>
+ <int key="relation">0</int>
+ <nil key="secondItem"/>
+ <int key="secondAttribute">0</int>
+ <float key="multiplier">1</float>
+ <object class="IBLayoutConstant" key="constant">
+ <double key="value">34</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="858711408"/>
+ <int key="scoringType">3</int>
+ <float key="scoringTypeFloat">9</float>
+ <int key="contentType">1</int>
+ </object>
+ </array>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">59</int>
+ <reference key="object" ref="185966605"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">61</int>
+ <reference key="object" ref="236413759"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">62</int>
+ <reference key="object" ref="708718284"/>
+ <reference key="parent" ref="858711408"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">63</int>
+ <reference key="object" ref="538246754"/>
+ <array class="NSMutableArray" key="children">
+ <object class="IBNSLayoutConstraint" id="172185075">
+ <reference key="firstItem" ref="538246754"/>
+ <int key="firstAttribute">8</int>
+ <int key="relation">0</int>
+ <nil key="secondItem"/>
+ <int key="secondAttribute">0</int>
+ <float key="multiplier">1</float>
+ <object class="IBLayoutConstant" key="constant">
+ <double key="value">34</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="538246754"/>
+ <int key="scoringType">3</int>
+ <float key="scoringTypeFloat">9</float>
+ <int key="contentType">1</int>
+ </object>
+ </array>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">64</int>
+ <reference key="object" ref="172185075"/>
+ <reference key="parent" ref="538246754"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">68</int>
+ <reference key="object" ref="549522802"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">70</int>
+ <reference key="object" ref="506804384"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">71</int>
+ <reference key="object" ref="294112825"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">72</int>
+ <reference key="object" ref="30504726"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">73</int>
+ <reference key="object" ref="746744863"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">74</int>
+ <reference key="object" ref="399235240"/>
+ <array class="NSMutableArray" key="children">
+ <object class="IBNSLayoutConstraint" id="25339159">
+ <reference key="firstItem" ref="399235240"/>
+ <int key="firstAttribute">8</int>
+ <int key="relation">0</int>
+ <nil key="secondItem"/>
+ <int key="secondAttribute">0</int>
+ <float key="multiplier">1</float>
+ <object class="IBLayoutConstant" key="constant">
+ <double key="value">34</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="399235240"/>
+ <int key="scoringType">3</int>
+ <float key="scoringTypeFloat">9</float>
+ <int key="contentType">1</int>
+ </object>
+ </array>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">75</int>
+ <reference key="object" ref="25339159"/>
+ <reference key="parent" ref="399235240"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">79</int>
+ <reference key="object" ref="967572429"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">80</int>
+ <reference key="object" ref="534867620"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">81</int>
+ <reference key="object" ref="458947079"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">82</int>
+ <reference key="object" ref="262554441"/>
+ <array class="NSMutableArray" key="children">
+ <object class="IBNSLayoutConstraint" id="146703890">
+ <reference key="firstItem" ref="262554441"/>
+ <int key="firstAttribute">8</int>
+ <int key="relation">0</int>
+ <nil key="secondItem"/>
+ <int key="secondAttribute">0</int>
+ <float key="multiplier">1</float>
+ <object class="IBLayoutConstant" key="constant">
+ <double key="value">34</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="262554441"/>
+ <int key="scoringType">3</int>
+ <float key="scoringTypeFloat">9</float>
+ <int key="contentType">1</int>
+ </object>
+ </array>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">83</int>
+ <reference key="object" ref="146703890"/>
+ <reference key="parent" ref="262554441"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">87</int>
+ <reference key="object" ref="945968116"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">88</int>
+ <reference key="object" ref="289565424"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">89</int>
+ <reference key="object" ref="154836529"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">90</int>
+ <reference key="object" ref="801664589"/>
+ <array class="NSMutableArray" key="children">
+ <object class="IBNSLayoutConstraint" id="350360023">
+ <reference key="firstItem" ref="801664589"/>
+ <int key="firstAttribute">8</int>
+ <int key="relation">0</int>
+ <nil key="secondItem"/>
+ <int key="secondAttribute">0</int>
+ <float key="multiplier">1</float>
+ <object class="IBLayoutConstant" key="constant">
+ <double key="value">34</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="801664589"/>
+ <int key="scoringType">3</int>
+ <float key="scoringTypeFloat">9</float>
+ <int key="contentType">1</int>
+ </object>
+ </array>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">91</int>
+ <reference key="object" ref="350360023"/>
+ <reference key="parent" ref="801664589"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">95</int>
+ <reference key="object" ref="874739352"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">97</int>
+ <reference key="object" ref="1013546937"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">98</int>
+ <reference key="object" ref="144899368"/>
+ <array class="NSMutableArray" key="children">
+ <object class="IBNSLayoutConstraint" id="888605777">
+ <reference key="firstItem" ref="144899368"/>
+ <int key="firstAttribute">8</int>
+ <int key="relation">0</int>
+ <nil key="secondItem"/>
+ <int key="secondAttribute">0</int>
+ <float key="multiplier">1</float>
+ <object class="IBLayoutConstant" key="constant">
+ <double key="value">34</double>
+ </object>
+ <float key="priority">1000</float>
+ <reference key="containingView" ref="144899368"/>
+ <int key="scoringType">3</int>
+ <float key="scoringTypeFloat">9</float>
+ <int key="contentType">1</int>
+ </object>
+ </array>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">99</int>
+ <reference key="object" ref="888605777"/>
+ <reference key="parent" ref="144899368"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">104</int>
+ <reference key="object" ref="154419028"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">106</int>
+ <reference key="object" ref="202359554"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">107</int>
+ <reference key="object" ref="392172463"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
+ <object class="IBObjectRecord">
+ <int key="objectID">108</int>
+ <reference key="object" ref="534252093"/>
+ <reference key="parent" ref="249263867"/>
+ </object>
</array>
</object>
<dictionary class="NSMutableDictionary" key="flattenedProperties">
<string key="-1.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
<string key="-2.CustomClassName">UIResponder</string>
<string key="-2.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="104.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="106.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="107.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="108.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
<string key="40.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
- <array key="40.IBViewMetadataConstraints">
+ <array class="NSMutableArray" key="40.IBViewMetadataConstraints">
<reference ref="927769008"/>
<reference ref="64945523"/>
<reference ref="591162250"/>
+ <reference ref="833081181"/>
+ <reference ref="873302976"/>
+ <reference ref="746744863"/>
+ <reference ref="185966605"/>
+ <reference ref="236413759"/>
+ <reference ref="294112825"/>
+ <reference ref="549522802"/>
+ <reference ref="506804384"/>
+ <reference ref="30504726"/>
+ <reference ref="967572429"/>
+ <reference ref="534867620"/>
+ <reference ref="458947079"/>
+ <reference ref="945968116"/>
+ <reference ref="289565424"/>
+ <reference ref="154836529"/>
+ <reference ref="874739352"/>
+ <reference ref="1013546937"/>
+ <reference ref="534252093"/>
+ <reference ref="154419028"/>
+ <reference ref="202359554"/>
+ <reference ref="392172463"/>
</array>
<string key="42.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
<boolean value="NO" key="42.IBViewMetadataTranslatesAutoresizingMaskIntoConstraints"/>
<string key="47.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
<string key="48.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
<string key="49.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="50.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <boolean value="NO" key="50.IBViewMetadataTranslatesAutoresizingMaskIntoConstraints"/>
+ <string key="52.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="55.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="56.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <array key="56.IBViewMetadataConstraints">
+ <reference ref="708718284"/>
+ </array>
+ <boolean value="NO" key="56.IBViewMetadataTranslatesAutoresizingMaskIntoConstraints"/>
+ <string key="59.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="61.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="62.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="63.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <array class="NSMutableArray" key="63.IBViewMetadataConstraints">
+ <reference ref="172185075"/>
+ </array>
+ <boolean value="NO" key="63.IBViewMetadataTranslatesAutoresizingMaskIntoConstraints"/>
+ <string key="64.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="68.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="70.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="71.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="72.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="73.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="74.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <array class="NSMutableArray" key="74.IBViewMetadataConstraints">
+ <reference ref="25339159"/>
+ </array>
+ <boolean value="NO" key="74.IBViewMetadataTranslatesAutoresizingMaskIntoConstraints"/>
+ <string key="75.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="79.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="80.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="81.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="82.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <array class="NSMutableArray" key="82.IBViewMetadataConstraints">
+ <reference ref="146703890"/>
+ </array>
+ <boolean value="NO" key="82.IBViewMetadataTranslatesAutoresizingMaskIntoConstraints"/>
+ <string key="83.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="87.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="88.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="89.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="90.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <array class="NSMutableArray" key="90.IBViewMetadataConstraints">
+ <reference ref="350360023"/>
+ </array>
+ <boolean value="NO" key="90.IBViewMetadataTranslatesAutoresizingMaskIntoConstraints"/>
+ <string key="91.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="95.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="97.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="98.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <array class="NSMutableArray" key="98.IBViewMetadataConstraints">
+ <reference ref="888605777"/>
+ </array>
+ <boolean value="NO" key="98.IBViewMetadataTranslatesAutoresizingMaskIntoConstraints"/>
+ <string key="99.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
</dictionary>
<dictionary class="NSMutableDictionary" key="unlocalizedProperties"/>
<nil key="activeLocalization"/>
<dictionary class="NSMutableDictionary" key="localizations"/>
<nil key="sourceID"/>
- <int key="maxID">49</int>
+ <int key="maxID">108</int>
</object>
<object class="IBClassDescriber" key="IBDocument.Classes"/>
<int key="IBDocument.localizationMode">0</int>
<bool key="IBDocument.PluginDeclaredDependenciesTrackSystemTargetVersion">YES</bool>
<int key="IBDocument.defaultPropertyAccessControl">3</int>
<bool key="IBDocument.UseAutolayout">YES</bool>
- <string key="IBCocoaTouchPluginVersion">1919</string>
+ <string key="IBCocoaTouchPluginVersion">1926</string>
</data>
</archive>
File XKCD1110/en.lproj/IVMainViewController_iPad.xib
<archive type="com.apple.InterfaceBuilder3.CocoaTouch.iPad.XIB" version="8.00">
<data>
<int key="IBDocument.SystemTarget">1536</int>
- <string key="IBDocument.SystemVersion">12A206j</string>
- <string key="IBDocument.InterfaceBuilderVersion">2519</string>
- <string key="IBDocument.AppKitVersion">1172.1</string>
- <string key="IBDocument.HIToolboxVersion">613.00</string>
+ <string key="IBDocument.SystemVersion">12C54</string>
+ <string key="IBDocument.InterfaceBuilderVersion">2840</string>
+ <string key="IBDocument.AppKitVersion">1187.34</string>
+ <string key="IBDocument.HIToolboxVersion">625.00</string>
<object class="NSMutableDictionary" key="IBDocument.PluginVersions">
<string key="NS.key.0">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
- <string key="NS.object.0">1856</string>
+ <string key="NS.object.0">1926</string>
</object>
<array key="IBDocument.IntegratedClassDependencies">
- <string>IBNSLayoutConstraint</string>
<string>IBProxyObject</string>
<string>IBUIBarButtonItem</string>
<string>IBUINavigationBar</string>
<string>IBUINavigationItem</string>
+ <string>IBUIScrollView</string>
<string>IBUIView</string>
</array>
<array key="IBDocument.PluginDependencies">
<reference key="NSNextResponder"/>
<int key="NSvFlags">274</int>
<array class="NSMutableArray" key="NSSubviews">
+ <object class="IBUIScrollView" id="19171963">
+ <reference key="NSNextResponder" ref="191373211"/>
+ <int key="NSvFlags">274</int>
+ <array class="NSMutableArray" key="NSSubviews">
+ <object class="IBUIView" id="518330023">
+ <reference key="NSNextResponder" ref="19171963"/>
+ <int key="NSvFlags">292</int>
+ <string key="NSFrameSize">{256, 256}</string>
+ <reference key="NSSuperview" ref="19171963"/>
+ <reference key="NSNextKeyView"/>
+ <string key="NSReuseIdentifierKey">_NS:9</string>
+ <object class="NSColor" key="IBUIBackgroundColor">
+ <int key="NSColorSpace">3</int>
+ <bytes key="NSWhite">MQA</bytes>
+ <object class="NSColorSpace" key="NSCustomColorSpace">
+ <int key="NSID">2</int>
+ </object>
+ </object>
+ <string key="targetRuntimeIdentifier">IBIPadFramework</string>
+ </object>
+ </array>
+ <string key="NSFrame">{{0, 44}, {768, 960}}</string>
+ <reference key="NSSuperview" ref="191373211"/>
+ <reference key="NSNextKeyView" ref="518330023"/>
+ <string key="NSReuseIdentifierKey">_NS:9</string>
+ <bool key="IBUIClipsSubviews">YES</bool>
+ <bool key="IBUIMultipleTouchEnabled">YES</bool>
+ <string key="targetRuntimeIdentifier">IBIPadFramework</string>
+ <float key="IBUIMaximumZoomScale">2048</float>
+ </object>
<object class="IBUINavigationBar" id="812863800">
<reference key="NSNextResponder" ref="191373211"/>
<int key="NSvFlags">290</int>
<string key="NSFrameSize">{768, 44}</string>
<reference key="NSSuperview" ref="191373211"/>
- <reference key="NSWindow"/>
+ <reference key="NSNextKeyView" ref="19171963"/>
<bool key="IBUIOpaque">NO</bool>
<bool key="IBUIClearsContextBeforeDrawing">NO</bool>
<string key="targetRuntimeIdentifier">IBIPadFramework</string>
</array>
<string key="NSFrame">{{0, 20}, {768, 1004}}</string>
<reference key="NSSuperview"/>
- <reference key="NSWindow"/>
<reference key="NSNextKeyView" ref="812863800"/>
<object class="NSColor" key="IBUIBackgroundColor">
<int key="NSColorSpace">3</int>
- <bytes key="NSWhite">MC4yNQA</bytes>
- <object class="NSColorSpace" key="NSCustomColorSpace">
- <int key="NSID">2</int>
- </object>
+ <bytes key="NSWhite">MQA</bytes>
</object>
+ <bool key="IBUIMultipleTouchEnabled">YES</bool>
<object class="IBUISimulatedStatusBarMetrics" key="IBUISimulatedStatusBarMetrics">
<int key="IBUIStatusBarStyle">2</int>
</object>
<int key="connectionID">3</int>
</object>
<object class="IBConnectionRecord">
+ <object class="IBCocoaTouchOutletConnection" key="connection">
+ <string key="label">scrollView</string>
+ <reference key="source" ref="372490531"/>
+ <reference key="destination" ref="19171963"/>
+ </object>
+ <int key="connectionID">17</int>
+ </object>
+ <object class="IBConnectionRecord">
+ <object class="IBCocoaTouchOutletConnection" key="connection">
+ <string key="label">xkcdView</string>
+ <reference key="source" ref="372490531"/>
+ <reference key="destination" ref="518330023"/>
+ </object>
+ <int key="connectionID">18</int>
+ </object>
+ <object class="IBConnectionRecord">
<object class="IBCocoaTouchEventConnection" key="connection">
<string key="label">showInfo:</string>
<reference key="source" ref="827738330"/>
</object>
<int key="connectionID">11</int>
</object>
+ <object class="IBConnectionRecord">
+ <object class="IBCocoaTouchOutletConnection" key="connection">
+ <string key="label">delegate</string>
+ <reference key="source" ref="19171963"/>
+ <reference key="destination" ref="372490531"/>
+ </object>
+ <int key="connectionID">19</int>
+ </object>
</array>
<object class="IBMutableOrderedSet" key="objectRecords">
<array key="orderedObjects">
<reference key="object" ref="191373211"/>
<array class="NSMutableArray" key="children">
<reference ref="812863800"/>
- <object class="IBNSLayoutConstraint" id="278524894">
- <reference key="firstItem" ref="812863800"/>
- <int key="firstAttribute">6</int>
- <int key="relation">0</int>
- <reference key="secondItem" ref="191373211"/>
- <int key="secondAttribute">6</int>
- <float key="multiplier">1</float>
- <object class="IBLayoutConstant" key="constant">
- <double key="value">0.0</double>
- </object>
- <float key="priority">1000</float>
- <reference key="containingView" ref="191373211"/>
- <int key="scoringType">8</int>
- <float key="scoringTypeFloat">29</float>
- <int key="contentType">3</int>
- </object>
- <object class="IBNSLayoutConstraint" id="1056034120">
- <reference key="firstItem" ref="812863800"/>
- <int key="firstAttribute">5</int>
- <int key="relation">0</int>
- <reference key="secondItem" ref="191373211"/>
- <int key="secondAttribute">5</int>
- <float key="multiplier">1</float>
- <object class="IBLayoutConstant" key="constant">
- <double key="value">0.0</double>
- </object>
- <float key="priority">1000</float>
- <reference key="containingView" ref="191373211"/>
- <int key="scoringType">8</int>
- <float key="scoringTypeFloat">29</float>
- <int key="contentType">3</int>
- </object>
- <object class="IBNSLayoutConstraint" id="643006596">
- <reference key="firstItem" ref="812863800"/>
- <int key="firstAttribute">3</int>
- <int key="relation">0</int>
- <reference key="secondItem" ref="191373211"/>
- <int key="secondAttribute">3</int>
- <float key="multiplier">1</float>
- <object class="IBLayoutConstant" key="constant">
- <double key="value">0.0</double>
- </object>
- <float key="priority">1000</float>
- <reference key="containingView" ref="191373211"/>
- <int key="scoringType">8</int>
- <float key="scoringTypeFloat">29</float>
- <int key="contentType">3</int>
- </object>
+ <reference ref="19171963"/>
</array>
<reference key="parent" ref="0"/>
</object>
<reference key="parent" ref="677504279"/>
</object>
<object class="IBObjectRecord">
- <int key="objectID">12</int>
- <reference key="object" ref="643006596"/>
- <reference key="parent" ref="191373211"/>
- </object>
- <object class="IBObjectRecord">
- <int key="objectID">13</int>
- <reference key="object" ref="1056034120"/>
+ <int key="objectID">15</int>
+ <reference key="object" ref="19171963"/>
+ <array class="NSMutableArray" key="children">
+ <reference ref="518330023"/>
+ </array>
<reference key="parent" ref="191373211"/>
</object>
<object class="IBObjectRecord">
- <int key="objectID">14</int>
- <reference key="object" ref="278524894"/>
- <reference key="parent" ref="191373211"/>
+ <int key="objectID">16</int>
+ <reference key="object" ref="518330023"/>
+ <reference key="parent" ref="19171963"/>
</object>
</array>
</object>
<string key="-2.CustomClassName">UIResponder</string>
<string key="-2.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
<string key="1.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
- <array key="1.IBViewMetadataConstraints">
- <reference ref="643006596"/>
- <reference ref="1056034120"/>
- <reference ref="278524894"/>
- </array>
<string key="10.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
- <string key="12.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
- <string key="13.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
- <string key="14.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="15.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
+ <string key="16.CustomClassName">IVXkcdView</string>
+ <string key="16.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
<string key="7.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
- <boolean value="NO" key="7.IBViewMetadataTranslatesAutoresizingMaskIntoConstraints"/>
<string key="8.IBPluginDependency">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
</dictionary>
<dictionary class="NSMutableDictionary" key="unlocalizedProperties"/>
<nil key="activeLocalization"/>
<dictionary class="NSMutableDictionary" key="localizations"/>
<nil key="sourceID"/>
- <int key="maxID">14</int>
+ <int key="maxID">19</int>
</object>
<object class="IBClassDescriber" key="IBDocument.Classes"/>
<int key="IBDocument.localizationMode">0</int>
<string key="IBDocument.TargetRuntimeIdentifier">IBIPadFramework</string>
<bool key="IBDocument.PluginDeclaredDependenciesTrackSystemTargetVersion">YES</bool>
<int key="IBDocument.defaultPropertyAccessControl">3</int>
- <bool key="IBDocument.UseAutolayout">YES</bool>
- <string key="IBCocoaTouchPluginVersion">1856</string>
+ <string key="IBCocoaTouchPluginVersion">1926</string>
</data>
</archive>
File XKCD1110/en.lproj/IVMainViewController_iPhone.xib
<archive type="com.apple.InterfaceBuilder3.CocoaTouch.XIB" version="8.00">
<data>
<int key="IBDocument.SystemTarget">1536</int>
- <string key="IBDocument.SystemVersion">12A269</string>
- <string key="IBDocument.InterfaceBuilderVersion">2835</string>
- <string key="IBDocument.AppKitVersion">1187</string>
- <string key="IBDocument.HIToolboxVersion">624.00</string>
+ <string key="IBDocument.SystemVersion">12C54</string>
+ <string key="IBDocument.InterfaceBuilderVersion">2840</string>
+ <string key="IBDocument.AppKitVersion">1187.34</string>
+ <string key="IBDocument.HIToolboxVersion">625.00</string>
<object class="NSMutableDictionary" key="IBDocument.PluginVersions">
<string key="NS.key.0">com.apple.InterfaceBuilder.IBCocoaTouchPlugin</string>
- <string key="NS.object.0">1919</string>
+ <string key="NS.object.0">1926</string>
</object>
<array key="IBDocument.IntegratedClassDependencies">
- <string>IBNSLayoutConstraint</string>
<string>IBProxyObject</string>
<string>IBUIButton</string>
+ <string>IBUIScrollView</string>
<string>IBUIView</string>
</array>
<array key="IBDocument.PluginDependencies">
<reference key="NSNextResponder"/>
<int key="NSvFlags">274</int>
<array class="NSMutableArray" key="NSSubviews">
+ <object class="IBUIScrollView" id="56958387">
+ <reference key="NSNextResponder" ref="883825266"/>
+ <int key="NSvFlags">274</int>
+ <array class="NSMutableArray" key="NSSubviews">
+ <object class="IBUIView" id="833447873">
+ <reference key="NSNextResponder" ref="56958387"/>
+ <int key="NSvFlags">292</int>
+ <string key="NSFrameSize">{256, 256}</string>
+ <reference key="NSSuperview" ref="56958387"/>
+ <reference key="NSWindow"/>
+ <reference key="NSNextKeyView" ref="558454645"/>
+ <string key="NSReuseIdentifierKey">_NS:9</string>
+ <object class="NSColor" key="IBUIBackgroundColor">
+ <int key="NSColorSpace">3</int> | __label__pos | 0.706366 |
Java Code Examples for org.pentaho.metadata.model.concept.types.LocalizedString#getLocalizedString()
The following examples show how to use org.pentaho.metadata.model.concept.types.LocalizedString#getLocalizedString() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
protected void exportLocalizedPropertiesRecursively( Properties props, IConcept parent, String locale ) {
for ( String propName : parent.getChildProperties().keySet() ) {
if ( parent.getChildProperty( propName ) instanceof LocalizedString ) {
// externalize string
String key = stringizeTokens( parent.getUniqueId() ) + ".[" + escapeKey( propName ) + "]";
LocalizedString lstr = (LocalizedString) parent.getChildProperty( propName );
String value = lstr.getLocalizedString( locale );
if ( value == null ) {
value = "";
}
props.setProperty( key, value );
}
}
if ( parent.getChildren() != null ) {
for ( IConcept child : parent.getChildren() ) {
exportLocalizedPropertiesRecursively( props, child, locale );
}
} else {
if ( logger.isDebugEnabled() ) {
logger.debug( "concept " + stringizeTokens( parent.getUniqueId() ) + " does not have children" );
}
}
}
Example 2
/**
* @param value
* @param type
* @return
*/
public Object getValue( final Object value, final Class type, final DataAttributeContext context ) {
if ( value == null ) {
return null;
}
if ( value instanceof LocalizedString == false ) {
return null;
}
if ( type == null || Object.class.equals( type ) || LocalizedString.class.equals( type ) ) {
if ( value instanceof LocalizedStringWrapper ) {
return value;
}
return new LocalizedStringWrapper( (LocalizedString) value );
}
if ( String.class.equals( type ) == false ) {
return null;
}
final LocalizedString settings = (LocalizedString) value;
final Locale locale = context.getLocale();
final String localeAsText = locale.toString();
final Object o = settings.getLocalizedString( localeAsText );
if ( o == null ) {
logger.warn( "Unable to translate localized-string property for locale [" + locale + "]. "
+ "The localization does not contain a translation for this locale and does not provide a fallback." );
}
return o;
}
Example 3
public String getName( String locale ) {
LocalizedString locName = getName();
if ( locName == null ) {
return getId();
}
String name = locName.getLocalizedString( locale );
if ( name == null || name.trim().length() == 0 ) {
return getId();
}
return name;
}
Example 4
public String getDescription( String locale ) {
LocalizedString locDesc = getDescription();
if ( locDesc == null ) {
return getId();
}
String name = locDesc.getLocalizedString( locale );
if ( name == null || name.trim().length() == 0 ) {
return getId();
}
return name;
}
Example 5
private String extractId(Concept item) {
LocalizedString localizedName = item.getName();
Set<String> locales = localizedName.getLocales();
if (locales.isEmpty()) return "";
// Just grab the first locale we come across
// This should normally only one for the star modeler
//
String locale = locales.iterator().next();
String id = localizedName.getLocalizedString(locale);
id = id.toUpperCase().replace(" ", "_");
return id;
}
Example 6
Source Project: pentaho-kettle File: ConceptUtil.java License: Apache License 2.0 4 votes vote down vote up
public static String getDescription(Concept concept, String locale) {
LocalizedString localizedString = (LocalizedString) concept.getProperty(Concept.DESCRIPTION_PROPERTY);
if (localizedString==null) return null;
return localizedString.getLocalizedString(locale);
}
Example 7
Source Project: pentaho-kettle File: ConceptUtil.java License: Apache License 2.0 4 votes vote down vote up
public static String getName(Concept concept, String locale) {
LocalizedString localizedString = (LocalizedString) concept.getProperty(Concept.NAME_PROPERTY);
if (localizedString==null) return null;
return localizedString.getLocalizedString(locale);
} | __label__pos | 0.999989 |
Blog Post
Why we owe it all to Alan Turing
Stay on Top of Enterprise Technology Trends
Get updates impacting your industry from our GigaOm Research Community
Join the Community!
It’s 100 years since the birth of Alan Turing — the brilliant British polymath scientist whose work informs and pervades all of modern computing. Despite a criminally shortened life, he made significant contributions in many fields: helping to break the German ciphers in WWII, designing some of the first digital computers, defining the field of Artificial Intelligence and conducting research in mathematics, biology and physics.
In fact he, more than anyone, can be said to be the father of the computer. So what was his great insight? What is it he did that shaped our world so profoundly?
The Turing Machine
Turing’s breakthrough came in 1936 in a paper called “On computable numbers, with an application to the Entscheidungsproblem”. Despite its opaque title, the thinking it held and work that directly followed from it caused a deep change. As a computer programmer, I see the insights Turing described in this paper in every single line of code I write.
This is where he defined what became known as the Turing Machine.
It’s a theoretical computer running programs that operate on data. It has an infinitely long paper tape on which it stores information. The tape is divided up into cells: each cell can be empty or can have a symbol in it. The machine reads the symbol from the current cell and decides what to do next. It can change the symbol in the current cell, or move the tape left or right by one cell.
But although it is extremely simple, this machine is capable of running a surprisingly large number of programs. In fact, Turing showed that any and every result that could be computed at all could be computed by a Turing Machine. Of course, it might take a very long time for the Turing Machine to complete the program, what with all that paper tape to move… but it could still do it.
And the idea that a simple machine like this can run any possible program turns out to be remarkably powerful. In fact, when combined with the work of Alonzo Church, an American mathematician who independently developed an equivalent theory, it was unstoppable.
The Church-Turing Thesis
Turing’s claim ended up combined with the work of Alonzo Church, the American mathematician who independently developed an equivalent theory. And their thesis turns out to be key: before Turing, machines performed one or two very specific tasks: for example, a loom wove cloth, it could not calculate the national debt. Turing had conceived of a machine you could program to solve almost any problem.
The Church-Turing Thesis has two very important implications.
First, it recognized the fundamental limitations of the system — for example, that there are some programs that are not computable by any machine.
But it was the second implication that was most profound: within its limitations, a Turing Machine can be programmed to run any piece of software. In fact, one of the programs that can be run on a Turing Machine is a simulation of a Turing Machine. And the simulated Turing Machine can itself run any program that a Turing Machine can run.
This is the genius of Turing’s work, his key insight. He has defined a “Universal Machine” — one that can run simulations so powerful they are themselves universal machines.
All of modern computing is underpinned by this notion. Every piece of software you use is running on layers of simulated computers that are as powerful as the physical hardware they’re running on — and as powerful as each other. A program running on a simulated Turing Machine works exactly the same way as one running on a non-simulated one; simulation has no effect on the complexity of the programs that can be run. In fact, a program does not even need to know if it running on a simulation or not.
This makes the hardware you are running irrelevant — at least in terms of what programs are possible, even if not how fast they run.
Programmers do not write code that runs on the hardware of their computers: they write code for a simulated computer running a high-level programming language, so instead of having to tediously write incomprehensible (and error-prone) strings of 1s and 0s, you can write easily understood code in Erlang or JavaScript or Ruby, or any of the dozens of programming languages. Each language is a Turing-compatible computer running on the Turing-compatible simulation below it.
Turing defined computing — his work was the key influence on John von Neumann, who created the architecture of the modern computer. Without his insight, computers would be quaint toys; instead they are at the heart of our world. As a programmer, I truly stand on the shoulders of giants… and nobody is more fundamental or important than Alan Turing.
11 Responses to “Why we owe it all to Alan Turing”
1. bayesrules
The title of Turing’s seminal article got truncated in the above article. It should be “On Computable Numbers, with an Application to the Entscheidungsproblem”
2. Sam Mellon
Thanks Dan for the wonderful article! It has been sometime since college, and thinking of Turing machines. And great to see you tying it effortlessly to the modern day tablet with the artwork. Enjoyed the read!
• bayesrules
I second this recommendation. It is a very interesting podcast.
I just realized that it was just 50 years ago, when Turing would have been 50 had he lived, that I wrote and tested a Turing machine simulator on the IBM 1620. This was an ideal machine for this task as its memory model consisted of a long addressable sequence of digits, much like the tape on a Turing machine. We used this program to investigate Tibor Rado’s “Busy Beaver Game.”
http://en.wikipedia.org/wiki/Busy_beaver
Rado had come to my undergraduate institution, Wesleyan, and had given a course on computability and Turing machines.
3. My favorite quote from the article:
“…you can write easily understood code in Erlang or JavaScript or Ruby…”
Yes, those are without a doubt the chosen languages of computer scientists everywhere when tasked with writing complex systems that need to be easily understood. | __label__pos | 0.807794 |
Containers
LXC vs Docker: Pros and Cons Explained
Discover the differences in capabilities, tooling, and functionality between LXC vs Docker containers. Understand the use cases for running apps and service deployments
Highlights
• Docker makes deploying app packages on a server in production environments much easier since all the application prerequisites, dependencies, and requirements are contained in the Docker container image platform.
• Note that Docker container images are still built on top of a Linux distro like Alpine Linux or some other lightweight design with the ability to run the app image.
• It also means, unlike a full virtual machine running on a hypervisor like VMware or openstack on bare metal, LXC containers do not emulate hardware.
When we start talking about running containers in the home lab or production, two types of containers usually come up in conversation for running services: LXC containers and Docker containers. This article will examine a comparison between LXC and Docker, helping you understand the differences in their capabilities, tooling, functionality, differences, and appropriate use cases for running apps and service deployments.
What are LXC containers?
LXC stands for Linux Container and is a pioneering technology in containerization. Some consider it to be the pure form of containers since it closely mimics a full virtual machine. As opposed to running full virtual machines, it provides a lightweight alternative requiring less utilization. It provides a virtual environment to create isolated processes and a network space without the full Linux operating system.
LXC leverages the Linux operating systems kernel of the host OS to create isolated environments, which essentially are like VMs but with less overhead. If you have used Proxmox, no doubt you know the containers you can easily create in Proxmox are LXC containers. However, you can use your favorite Linux distro, like Ubuntu, and install LXC containers.
When you right-click on your PVE node, you can choose the Create CT option which will create a new LXC container.
Creating an lxc container in proxmox
Creating an lxc container in proxmox
The Architecture of LXC Containers
LXC containers (Linux containers) are known for being simple and efficient. They operate by creating a separate operating system environment within the host system to create multiple isolated environments.
Unlike virtual machines that require their own kernel, LXC containers share the host’s kernel, making them more efficient regarding resource usage. LXC containers sit somewhere in the middle of an enhanced chroot and a full-fledged virtual machine. It also means, unlike a full virtual machine running on a hypervisor like VMware or openstack on bare metal, LXC containers do not emulate hardware.
Despite sharing the host kernel, they have their own file system and provide an effective boundary of separation between the LXC environment and the host. LXC containers require some prior Linux knowledge and basic command line experience running Linux bash commands.
What is Docker?
Since its introduction, Docker has dramatically changed the way applications are run in production and even how code is developed. Docker containers are lightweight, portable, and easy to manage. They have also changed how developers build and deploy applications and Docker solved many of the challenges with full virtual machines and CI/CD deployments, performance, along with compatibility between different Dev environments.
Docker makes deploying app packages on a server in production environments much easier since all the application prerequisites, dependencies, and requirements are contained in the Docker container image platform. Automation scripts can easily handle the creation, configuration, and updating of containers.
Note that Docker container images are still built on top of a Linux distro like Alpine Linux or some other lightweight design with the ability to run the app image. Other popular Docker solutions allow running common database applications, Java, Python, and other apps.
The Docker Container Ecosystem
Docker extends beyond just creating containers. It encompasses an entire ecosystem, including the Docker daemon, Docker Hub registry, Docker Engine, and Docker Images, which collectively simplify the process of building, shipping, and running applications.
Using a prebuilt Docker image, developers and DevOps engineers can easily spin up popular application in development and production.
LXC vs Docker: Comparing the key differences
When comparing LXC and Docker, it’s essential to understand their fundamental differences. LXC is often seen as a more “pure” form of containerization, offering system containers that closely mimic virtual machines. Docker, on the other hand, focuses on application containers designed to run specific applications.
Take note of the following table comparing the two, and then we will compare a few characteristics:
AspectLXC (Linux Containers)Docker
Primary FocusSystem containers that mimic virtual machinesApplication containers for deploying and running apps
Container TypeMore akin to traditional VMs, offering OS-level virtualizationFocuses on application-level virtualization
Kernel SharingShares the host’s kernel, but can run different Linux distributionsShares the host’s kernel, typically the same distribution
Resource OverheadLower than VMs, slightly higher than DockerLower than both VMs and LXC
SecurityRelies on Linux kernel security, less isolation than DockerStronger isolation, less dependent on host kernel
EcosystemPrimarily the container runtime environmentExtensive ecosystem including Docker Hub, Docker Engine
PortabilityGood, but less than Docker due to OS-level virtualizationExcellent, due to app-level virtualization
Use CasesSuitable for running multiple services in one containerIdeal for microservices, CI/CD pipelines, rapid deployment
Community and SupportStrong community, less corporate backing than DockerVery large community, strong corporate support
ConfigurationMore complex, closer to traditional VM configurationSimpler, more straightforward configuration
StorageUses filesystems attached to the host systemUtilizes Docker images for storage and versioning
NetworkingSimilar to VMs, more complex setupSimplified networking, easier port mapping
ScalabilityGood for scaling verticallyBetter suited for horizontal scaling
FlexibilityMore flexible in terms of OS environmentMore focused on app environment, less OS flexibility
DeploymentSlower deployment compared to DockerRapid deployment capabilities
OrchestrationLimited native support, relies on external toolsIntegrated with Docker Swarm, compatible with Kubernetes
PerformanceGenerally good, but depends on the workloadOptimized for high performance, especially for stateless apps
IsolationOS-level isolationProcess-level isolation, stronger app separation
LXC vs Docker comparison
1. Use Cases
Note the following comparison of system containers vs application containers.
System Containers vs Application Containers
System containers provided by LXC are suitable for running a full-fledged operating system, offering an experience similar to virtual machines. Docker containers, however, are tailored for running specific applications, ensuring that each application runs in a completely isolated environment.
Understanding where LXC and Docker are the best fit is important to choose the right tool for the right job.
Choosing the right tool for the right job
Choosing the right tool for the right job
When to Choose LXC
LXC is ideal for scenarios where you need lightweight virtualization close to a full OS experience. It’s perfect for running multiple applications on the same Linux system or for situations where you need the flexibility of a virtual machine without the associated overhead.
Docker’s Ideal Scenarios
Docker shines in application deployment and scaling. It’s the go-to choice for microservices architecture, CI/CD pipelines, and rapid application development and deployment. Docker’s portability makes it a favorite for cloud-based applications.
2. Security Considerations of LXC vs Docker
No discussion about container technologies is complete without addressing security. Both LXC and Docker offer robust security features, but their approaches differ.
Lxc vs docker security considerations
Lxc vs docker security considerations
Security in LXC Containers
LXC’s approach to security revolves around Linux kernel features. It leverages namespaces and cgroups to create isolated environments. However, since LXC containers share the same kernel as the host, any vulnerabilities in the kernel can potentially affect all containers.
Docker’s Security Model
Docker’s security model is more granular when copared to LXC, offering additional layers of isolation and less dependency on the host system’s kernel. Docker containers are less likely to affect each other or the host system, making them a safer choice in multi-tenant environments.
3. Orchestration
What about container orchestration with LXC vs Docker for management and scalability? Docker has a native orchestration tool called Docker Swarm. When you have multiple Docker container hosts, you can enable Swarm mode for your container hosts and Docker Swarm will schedule containers and provide high availability and orchestration for your containers.
Orchestration lxc vs docker
Orchestration lxc vs docker
LXC doesn’t have a native orchestration tool in Linux to schedule LXCs comparable to running Docker containers in Swarm. However, there are a few community projects that ones have worked on to do some LXC scheduling. Also, Hashicorp Nomad has an LXC driver for scheduling tasks using LXC: Drivers: LXC | Nomad | HashiCorp Developer.
As a note, why didn’t we mention Kubernetes? Recently, Kubernetes has made the shift from Docker containers as the container runtime to containerd for container services. Interestingly, you can also run Kubernetes in Docker using a tool called K3D.
4. Backups
If you are like me, one of the areas of a technology that you automatically consider is how do you protect that specific technology. How do you backup your containers? LXC containers have a very easy way to be backed up, especially if you are running Proxmox. Proxmox Backup Server natively backs up your LXC containers.
Lxc vs docker backups
Lxc vs docker backups
Backing up Docker containers can be a mixed bag of tools. Typically, most when running Docker containers run persistent volumes that allow mounting local storage from the Docker host to pass into the Docker container state. Backing up Docker usually involves backing up this persistent data and then simply repulling the container image and mounting the data.
There are a few solutions out there like the Duplicati solution that I have written about before:
Backup Docker Volumes with Duplicati and Docker Compose
5. Networking
Networking is an important component of running containers. LXC containers take advantage of the native Linux networking constructs like Linux bridge devices or Linux VLANs.
Docker on the other hand has its own networking constructs:
• Bridge: This is the standard network driver used by default.
• Host: This driver removes network isolation, allowing the container to directly interact with the Docker host.
• None: This option ensures total isolation of a container from the host and other containers.
• Overlay: Used for connecting multiple Docker daemons, creating a network overlay.
• IPvlan: Allows detailed control over both IPv4 and IPv6 addresses within networks.
• Macvlan: Enables the assignment of a unique MAC address to a container.
6. Platform compatibility
One of the important things to consider with LXC vs Docker containers is platform compatibility. With LXC containers, they by nature only compatible with Linux operating systems. However, Docker can run on Linux, Windows, and macOS, making it much more platform independent.
However, there are some restrictions here as well as you must make sure the Docker image is a Windows Docker image or a Linux Docker image as the kernel requirements must match or you will run into issues running Docker on your servers. Many work around this by running a Linux VM on top of Windows, or vice versa. Of course, you can also run LXC containers on a Windows platform if you run them in a Linux VM.
6. Future of LXC vs Docker
As container technologies evolve, both LXC and Docker continue to play significant roles in shaping the future of software development and deployment.
Lxc vs docker the future
Lxc vs docker the future
Innovations in LXC
LXC is continuously improving, focusing on enhancing its system container capabilities, security features, and integration with existing Linux systems.
Docker’s Ongoing Evolution
Docker, always at the forefront of containerization technology, is constantly evolving. Its focus remains on simplifying application containerization, improving security, and enhancing portability across different environments.
Frequently Asked Questions About LXC and Docker
How do LXC and Docker utilize the Linux kernel for containerization?
LXC leverages Linux kernel features such as cgroups and namespaces to provide an environment close to traditional virtual machines but with lower overhead. Docker also uses these features, but focuses more on isolated processes for each application, ensuring that each Docker container is lightweight and portable.
What are the security implications of using LXC and Docker?
Security in LXC is dependent on the Linux kernel’s built-in features. Since LXC containers share the kernel with the host, vulnerabilities in the kernel can affect them. Docker, however, adds more isolation layers, reducing the dependency on the host’s kernel and offering a more secure environment for running containers.
Can Docker and LXC be used together for containerization?
Yes, Docker and LXC can be used in tandem. For instance, Docker can be used for its efficient application containerization and rapid deployment capabilities, while LXC can be utilized for situations that require a full operating system environment within a container.
What are the main differences in resource usage between Docker and LXC?
Docker containers are generally more resource-efficient compared to LXC, especially when running multiple isolated processes for different applications. LXC, while efficient compared to virtual machines, may consume more resources when used for full-fledged operating system environments.
How do Docker Swarm and LXC compare in terms of container orchestration?
Docker Swarm is a native clustering and orchestration tool for Docker containers, enabling users to manage multiple Docker containers as a single system. LXC doesn’t have a native orchestration tool like Docker Swarm, but it can be integrated with external tools for managing multiple LXC containers.
What is the role of Docker Hub in the Docker ecosystem?
Docker Hub acts as a public repository for Docker images, allowing users to share and access container images. It’s an important part of the Docker ecosystem, making the distribution and version control of Docker images easier and more convenient.
In what scenarios would LXC be preferred over Docker?
LXC would be preferred in scenarios requiring a lightweight alternative to full virtual machines, such as running multiple applications on a single Linux system or when the overhead of a complete virtual machine is unnecessary. LXC is also useful for users who need a more traditional Linux environment within their containers.
What are the advantages of Docker’s application containers in development environments?
Docker’s application containers offer advantages like portability, quick startup times, and consistent environments across different stages of development. This makes Docker ideal for continuous integration and continuous deployment (CI/CD) pipelines and microservice architecture.
Does using LXC require prior Linux knowledge?
Having an understanding of the Linux operating system and Linux kernel features can be helpful when working with LXC, as it makes use of Linux constructs. However, basic container operations with LXC can be performed without in-depth Linux knowledge.
Wrapping up LXC vs Docker containers
Both LXC containers and Docker containers provide many benefits and capabilities when compared to running full virtual machines. For this reason, containers have become the de facto standard for running modern cloud workloads across the Internet. Most apps in the cloud support containerized deployments and migration.
Containers are not a drop-in replacement for virtual machines, but they do work hand-in-hand with VMs to provide a scalable, resilient, and microservices architecture. This comparison of LXC vs Docker helps to differentiate between the two types of containers and their use cases. Let me know in the comments what types of containers you are using and what use cases.
Subscribe to VirtualizationHowto via Email 🔔
Enter your email address to subscribe to this blog and receive notifications of new posts by email.
Brandon Lee
Brandon Lee is the Senior Writer, Engineer and owner at Virtualizationhowto.com and has over two decades of experience in Information Technology. Having worked for numerous Fortune 500 companies as well as in various industries, He has extensive experience in various IT segments and is a strong advocate for open source technologies. Brandon holds many industry certifications, loves the outdoors and spending time with family. Also, he goes through the effort of testing and troubleshooting issues, so you don't have to.
Related Articles
One Comment
Leave a Reply
Your email address will not be published. Required fields are marked *
This site uses Akismet to reduce spam. Learn how your comment data is processed. | __label__pos | 0.847754 |
Home Answers Viewqa Ajax table structure
Share on Google+Share on Google+
V.A.G.Raju
table structure
1 Answer(s) 5 years and 3 months ago
Posted in : Ajax
Advertisement
Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.
Have Programming Question? Ask it here!
View Answers
September 17, 2008 at 7:44 PM
Use this code, no need to change, As per your database scenario, I design.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Data extends HttpServlet {
private int countryID;
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{
String value = req.getParameter("country");
String dbQuery1 = "Select country_ID FROM TB_countries WHERE country_name='" + value + "'";
String dbQuery2 = "";
PrintWriter out = res.getWriter();
String result="";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ashok";, "root", "mysql");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(dbQuery1);
while(rs.next()){
countryID = rs.getShort("country_ID");
}
dbQuery2 = "Select state_name FROM TB_states WHERE country_ID=" + countryID;
rs = stmt.executeQuery(dbQuery2);
while(rs.next()){
result = result + rs.getString("state_name") + ",";
}
}catch(Exception ex){
System.out.println(ex.getMessage());
}
out.write(result);
}
}
Thanks
Rajanikant
Related Pages:
table structure - Ajax
table structure This is my table structures.Please modify the code. TB_countries +--------------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra
structure in JSP
structure in JSP How do I achieve structure in JAVA or JSp
Array of structure
Array of structure create employment details with necessary field using array of structure
Advertisement
structure example
structure example in the example above what do you call the names student1,student2 and student3 Post the code
C Structure
C Structure Respected sir, Can a structure in C contain a pointer to itself ? if yes means how sir ? plz help me sir
Data structure
Data structure: How to sort numbers in a queue using a bubble sort method? How to sort numbers in a queue using a bubble sort method
inbox structure
inbox structure I want to create an inbox for my project in which records are to be fetched dynamically. I am using netbeans (jsp + javascript+ servlet.) The structure is same like yahoo inbox (1st column full of check boxes
Mysql Alter Table Identity
Mysql Alter Table Identity Mysql Alter Table Identity is used to change the existing structure of table and add ID column as identity key that is used to uniquely define
mysqldump structure only
mysqldump structure only Hi, How to take dump of database structure only? Provide me the syntax to take mysqldump structure only. Thanks Hi, You can use -d option with mysqldump command to take the structure only
Drop Table
Drop Table Drop Table in SQL get rid of an object or table from the database. Using a drop Query get rid of all the rows deleted from the table and the structure is removed
table
table multiplicatyion table
use tables to structure forms
use tables to structure forms How can I use tables to structure forms
tables to structure forms
tables to structure forms How can I use tables to structure forms
use tables to structure forms
use tables to structure forms How can I use tables to structure forms
tables to structure forms
tables to structure forms How can I use tables to structure forms
MySQL Directory Structure
MySQL Directory Structure ... scale sequence search the approaches as well as mysql table. These table dumps... the installation. The MySQL support Ensemble downloading of many correlation table
TABLE
TABLE Why doesn't <TABLE WIDTH="100%"> use the full browser width
Table
Table How i generate table in showMessageDialog. I want that i creat a table and run in showMessageDialogeprint("cprint("code sample");ode sample
Mlm tree structure
Mlm tree structure i want mlm tree structure code in php with jquery or Ajax
Mlm tree structure
Mlm tree structure i want mlm tree structure code in php with jquery or Ajax
Mlm tree structure
Mlm tree structure i want mlm tree structure code in php with jquery or Ajax
MLM tree structure
MLM tree structure i want mlm tree structure code in php .Please help me..... thanks in advance
Table
Table How I generate table in showMessageDialog. E.g 3X1=3 3X2=6 3X3=9print("code sample
Table
Table How i generate table in showMessageDialog. I want to creat a table and run in showMessageDialoge. Pl make a table programe which run..., JOptionpane, Integer.parseInt. Please use only these above methods to make table
table
input from oracle table(my database table..) This is a very important table of my
table
table Hi..I have a list of links which links to a table in the same page.If I click first link the table is displayed at the top, likewise if i click the last link the table is displayed at the last,i dont know how to set
Table
Table How i generate table in JOptionpane.showMessageDialog... advance coding but i want u make the table using JOptionpane.showMessageDialog, import.javax.swing int Integer.parseInt(). Thats my limit. Pl generata a table
Directory structure of a web application
Directory structure of a web application Explain the directory structure of a web application. The directory structure of a web application consists of two parts. A private directory called WEB-INF. A public
What is the structure of Spring framework?
What is the structure of Spring framework? What is the structure of Spring framework? Hi, In Java Spring framework offers one-stome... Framework structure this link. Thanks
table?
table? Hi, how could i make a table in javascript, which would look like this: AA CODON Number /1000 Fraction .. (this row... can't figure out, how to construct a table,with two fixed columns, one that reads
Table
Table Why u dont understand sir?? I want to make a table program which generate a table on showMessageDialog. I have learnt these methods until now... methods to be used. Write a table program which use only and only these above methods
cylinder tree structure
materials in a hierarchical structure in a cylinder form. for example my interface... code to create the tree structure. your advice will be very very appreciated
Table
Table How i create table on showMessageDialog using JOptionpane and Integer.parseInt. No other method to use. Pl make a program which generate 5X1=5 5X2=10 5X3=15 Hi Friend, Try this: import javax.swing.*; import
Structure of Web Module
In this section, you will learn the structure of the web module
EJB directory structure
EJB directory structure The tutorial is going to explain the standard directory structure of an EJB... the servlet and JSP pages. Figure: EJB Directory Structure in NetBeans Above
Tree Structure Catalogue Menu Display
Tree Structure Catalogue Menu Display How best can I display a tree structure for a catalogue menu ? One option is to use an applet, but theres a 30000 node limit to the one im using. Is there any way other than an applet
REGARDING TREE STRUCTURE IN STRUTS - Struts
REGARDING TREE STRUCTURE IN STRUTS Hello friends, I need ur help its urgent requirement. I need a dynamic tree structure format i.e I have created... in the database should be shown in the jsp(struts) as an tree structure form
C Structure Pointer
C Structure Pointer This section illustrates you the concept of Structure Pointer in C. You... through structure pointer. For that, we declare the structure type st consisting
java programming structure - Java Beginners
java programming structure java programming structure Hi Friend, The structure of Java programme is: [Package declarations] [Import statements] [Class declaration] [Method declaration] eg: package
The JDK Directory Structure
Directory structure of JDK Welcome to Java tutorial series. In this lesson, you will learn about the directory structure of Java Development Kit, JDK. Since... structure. On your screen, you can see the directory structure of JDK as well as JRE
Web Application Directory Structure:
Web Application Directory Structure: To develop an application using servlet or jsp make the directory structure like... to this directory structure: Roseindia/ WEB
ADT ,data structure (ArrayList), sorting
ADT ,data structure (ArrayList), sorting Write a program to calculate a bonus for 10 employees of WAFA Supermarket. The program consists of an abstract class Employee. Each employee contains IC number, name, basicSalary
Structure of Java Arrays
Structure of Java Arrays Now lets study the structure of Arrays in java. Array is the most widely used data structure in java. It can contain multiple values of the same
PHP Alternative Control Structure
Alternative Control Structure: PHP provides alternative ways to use control... structure we can replace the opening brace with a colon(:) and the closing brace... coding within any control structure, the examples are given below: elseif
EJB directory structure
EJB directory structure The tutorial is going to explain the standard directory structure of an EJB... the servlet and JSP pages. Figure: EJB Directory Structure in NetBeans Above
Java SDK Directory Structure
Java SDK Directory Structure This section introduces the Directory and file structure... information bellow. SDK Directory Structure: Subdirectories of the SDK
Tree data structure
Description: A tree data structure that are based on hierarchical tree structure with sets of nodes. A tree is a acyclic connected graph with zero or more children nodes and at most one parent nodes. Code: #include <stdio.h>
How to Display Data in a tree structure on the GUI
How to Display Data in a tree structure on the GUI how to display data in a tree structure on the GUI? I need this sort of UI to display data showing a set of rules showing various conditions and the actions related
how to create this structure in json using grails
how to create this structure in json using grails { "query": { "type": "cluster", "view": "accountActivity", "regions": [2342,334,241,13], "companies": [43228583,433421683,342427783], "departments": [1,2,4,6], "brands
Advertisements
| __label__pos | 0.935551 |
@DeveloperMemes If I understand it correctly, the last statement is actually an indication, that the passwords are not safe at this service, since they are stored in plain text instead of hashes. You shouldn't register here at all. Am I correct?
@DeveloperMemes @marmarper If a service is stupid enough to tell you when a password has already been used, it very possibly also stores them in clear text.
But it can also mean that passwords are being hashed, but are not being salted, so by comparing two hashes, you can tell if they stand for the same password. Not using salted hashes makes them vulnerable to attacks that involve comparing hashes to a series of precomputed hashes and allow an attacker that knows the password for one account to get access to other accounts with the same password.
@marmarper @DeveloperMemes the passwords could still be hashed in this situation, but if so they couldn't be salted -- which, these days, is almost as stupid as not hashing the passwords in the first place.
@marmarper @DeveloperMemes you can figure out duplicate passwords even when using salted Argon2.
For every row in the database calculate the hashed password given the user-specific salt. If there's a duplicate you can find it even without storing anything insecure.
It also does not require any brute force.
It's pretty stupid b/c these hash algorithms are purposefully intense in calculations
@DeveloperMemes Now I am thinking about it, these imposed password policies are just facilitating password brute force. if we think about it. We may make the cardinality bigger, but then substract a whole big chuck of possibilities.
Sign in to participate in the conversation
Mastodon
cybre.town is an instance of Masterdon, a decentrialized and open source social media plattform. This instance is especially about tech/cyber stuff and is also available inside the tor network. - The name is inspired by cybre.space. | __label__pos | 0.551323 |
Question: Do Ipads Have Built In WiFi?
Do ipads have their own wifi?
WiFi-Only iPad A WiFi-only model iPad connects to the Internet using wireless or WiFi access.
A WiFi-only model iPad cannot be made into a cellular data service iPad.
It does not have the components that allow for cellular data service..
How can I get Internet on my iPad without WIFI?
How to connect an iPad to the Internet without Wifi, Step by Step instructions:Turn on both devices.On your wifi-device, turn on the personal hot spot.Connect the iPod/iPad to the personal hot spot.BAM! You should be able to use the iPod/iPad out in the community.
Why can’t I get FaceTime on my iPad?
Go to Settings and tap Cellular or tap Mobile Data, then turn on FaceTime. If you’re using an iPad, you might see Settings > Cellular Data. Go to Settings > FaceTime and make sure that FaceTime is on. If you see ‘Waiting for Activation’, turn FaceTime off and then on again.
How do I get FaceTime on my iPad?
Set up FaceTime on iPadGo to Settings > FaceTime, then turn on FaceTime.If you want to be able to take Live Photos during FaceTime calls, turn on FaceTime Live Photos.Enter your phone number, Apple ID, or email address to use with FaceTime.
How much is data plan for iPad?
Finally, Mobile Share Data are monthly data plans ranging from 4GB to 50GB that also include a $10 montly access charge. When it comes to overage charges, it will cost you $10 per additional GB on either plan….DataConnect Pass with Auto Renew.DataPrice1GB$19.99 (monthly)7GB$55 (monthly)25GB$34.992 (monthly)Mar 19, 2020
How do I get internet for my iPad?
Make sure your iPad has Wi-Fi connection enabledTap on Settings.Tap on Wi-Fi in the left column.When Wi-Fi comes up in the right column, tap on the toggle next to Wi-Fi so it’s green.If you already have a preferred Wi-Fi, it should come up automatically.More items…•
How do I know if my iPad is wifi only?
You can quickly tell if your iPad is capable of mobile connectivity by looking for the SIM card slot on the side. If you see one then it’s a Wi-Fi + cellular model. If not, then it’s Wi-Fi-only.
Do you need data plan for iPad?
Based on my experience with an older iPad with wifi & cellular, the answer is no, you don’t need a data plan if you only want to use wifi connectivity. I never did get a cellular plan for my iPad. … Data plan is only needed if you wish to activate the cellular capabilities. Otherwise, you can just use wifi.
Should I get iPad with cellular or just WiFi?
In short, if your iPad rarely leaves your home and don’t want to deal with carriers and data plans, get the WiFi-only iPad. And if there’s ever a dire need to have it connect to the internet with no wireless networks around, you can always use the hotspot feature of your phone.
Do I need cellular on my iPad to FaceTime?
Unlike iPhones, iPads can’t connect to cellular networks, so you will need to have Internet access to make FaceTime work.
Can I get data on my iPad?
If you have a Wi-Fi + Cellular model iPad, you can sign up for a cellular data plan. This helps you stay connected when you’re away from a Wi-Fi hotspot.
Can I use my iPad as a phone?
iPad Phone: How to Use iPad as phone to make calls and text for free (iPhone and Android too) Use an iPad as phone to make calls and text. A few free apps will turn your iPad or iPad Mini into an iPad phone with unlimited texting and calling within the US.
Is there a monthly fee for iPad?
There is a fee to purchase the iPad device and also a monthly fee for the cellular data service with a monthly data transfer limit. … Depending on the carrier, the iPad model, and your location, you may have various cellular plan options including in some cases the choice of 3G or 4G cellular data service.
Should I get cellular on my iPad?
A WiFi Only iPad can only connect to data (and say, browse the internet or download emails) if there is a WiFi network available which you can connect to. So if you plan to be out an about a lot with your iPad, getting one with cellular can be a great option.
How can I get Internet on my tablet without WiFi?
How To Get Internet On Tablet Without WiFiTry to Use the Mobile Hotspot: It is not completely free, however, if you have large data plans then you can make your mobile as a Wi-Fi modem and surf the internet whenever you want. … Using a Wi-Fi Finding App: … By using Wi-Fi dongle: … Share the internet of someone else: | __label__pos | 0.969724 |
LAPACK 3.8.0
LAPACK: Linear Algebra PACKage
◆ dtbtrs()
subroutine dtbtrs ( character UPLO,
character TRANS,
character DIAG,
integer N,
integer KD,
integer NRHS,
double precision, dimension( ldab, * ) AB,
integer LDAB,
double precision, dimension( ldb, * ) B,
integer LDB,
integer INFO
)
DTBTRS
Download DTBTRS + dependencies [TGZ] [ZIP] [TXT]
Purpose:
DTBTRS solves a triangular system of the form
A * X = B or A**T * X = B,
where A is a triangular band matrix of order N, and B is an
N-by NRHS matrix. A check is made to verify that A is nonsingular.
Parameters
[in]UPLO
UPLO is CHARACTER*1
= 'U': A is upper triangular;
= 'L': A is lower triangular.
[in]TRANS
TRANS is CHARACTER*1
Specifies the form the system of equations:
= 'N': A * X = B (No transpose)
= 'T': A**T * X = B (Transpose)
= 'C': A**H * X = B (Conjugate transpose = Transpose)
[in]DIAG
DIAG is CHARACTER*1
= 'N': A is non-unit triangular;
= 'U': A is unit triangular.
[in]N
N is INTEGER
The order of the matrix A. N >= 0.
[in]KD
KD is INTEGER
The number of superdiagonals or subdiagonals of the
triangular band matrix A. KD >= 0.
[in]NRHS
NRHS is INTEGER
The number of right hand sides, i.e., the number of columns
of the matrix B. NRHS >= 0.
[in]AB
AB is DOUBLE PRECISION array, dimension (LDAB,N)
The upper or lower triangular band matrix A, stored in the
first kd+1 rows of AB. The j-th column of A is stored
in the j-th column of the array AB as follows:
if UPLO = 'U', AB(kd+1+i-j,j) = A(i,j) for max(1,j-kd)<=i<=j;
if UPLO = 'L', AB(1+i-j,j) = A(i,j) for j<=i<=min(n,j+kd).
If DIAG = 'U', the diagonal elements of A are not referenced
and are assumed to be 1.
[in]LDAB
LDAB is INTEGER
The leading dimension of the array AB. LDAB >= KD+1.
[in,out]B
B is DOUBLE PRECISION array, dimension (LDB,NRHS)
On entry, the right hand side matrix B.
On exit, if INFO = 0, the solution matrix X.
[in]LDB
LDB is INTEGER
The leading dimension of the array B. LDB >= max(1,N).
[out]INFO
INFO is INTEGER
= 0: successful exit
< 0: if INFO = -i, the i-th argument had an illegal value
> 0: if INFO = i, the i-th diagonal element of A is zero,
indicating that the matrix is singular and the
solutions X have not been computed.
Author
Univ. of Tennessee
Univ. of California Berkeley
Univ. of Colorado Denver
NAG Ltd.
Date
December 2016
Definition at line 148 of file dtbtrs.f.
148 *
149 * -- LAPACK computational routine (version 3.7.0) --
150 * -- LAPACK is a software package provided by Univ. of Tennessee, --
151 * -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..--
152 * December 2016
153 *
154 * .. Scalar Arguments ..
155 CHARACTER diag, trans, uplo
156 INTEGER info, kd, ldab, ldb, n, nrhs
157 * ..
158 * .. Array Arguments ..
159 DOUBLE PRECISION ab( ldab, * ), b( ldb, * )
160 * ..
161 *
162 * =====================================================================
163 *
164 * .. Parameters ..
165 DOUBLE PRECISION zero
166 parameter( zero = 0.0d+0 )
167 * ..
168 * .. Local Scalars ..
169 LOGICAL nounit, upper
170 INTEGER j
171 * ..
172 * .. External Functions ..
173 LOGICAL lsame
174 EXTERNAL lsame
175 * ..
176 * .. External Subroutines ..
177 EXTERNAL dtbsv, xerbla
178 * ..
179 * .. Intrinsic Functions ..
180 INTRINSIC max
181 * ..
182 * .. Executable Statements ..
183 *
184 * Test the input parameters.
185 *
186 info = 0
187 nounit = lsame( diag, 'N' )
188 upper = lsame( uplo, 'U' )
189 IF( .NOT.upper .AND. .NOT.lsame( uplo, 'L' ) ) THEN
190 info = -1
191 ELSE IF( .NOT.lsame( trans, 'N' ) .AND. .NOT.
192 $ lsame( trans, 'T' ) .AND. .NOT.lsame( trans, 'C' ) ) THEN
193 info = -2
194 ELSE IF( .NOT.nounit .AND. .NOT.lsame( diag, 'U' ) ) THEN
195 info = -3
196 ELSE IF( n.LT.0 ) THEN
197 info = -4
198 ELSE IF( kd.LT.0 ) THEN
199 info = -5
200 ELSE IF( nrhs.LT.0 ) THEN
201 info = -6
202 ELSE IF( ldab.LT.kd+1 ) THEN
203 info = -8
204 ELSE IF( ldb.LT.max( 1, n ) ) THEN
205 info = -10
206 END IF
207 IF( info.NE.0 ) THEN
208 CALL xerbla( 'DTBTRS', -info )
209 RETURN
210 END IF
211 *
212 * Quick return if possible
213 *
214 IF( n.EQ.0 )
215 $ RETURN
216 *
217 * Check for singularity.
218 *
219 IF( nounit ) THEN
220 IF( upper ) THEN
221 DO 10 info = 1, n
222 IF( ab( kd+1, info ).EQ.zero )
223 $ RETURN
224 10 CONTINUE
225 ELSE
226 DO 20 info = 1, n
227 IF( ab( 1, info ).EQ.zero )
228 $ RETURN
229 20 CONTINUE
230 END IF
231 END IF
232 info = 0
233 *
234 * Solve A * X = B or A**T * X = B.
235 *
236 DO 30 j = 1, nrhs
237 CALL dtbsv( uplo, trans, diag, n, kd, ab, ldab, b( 1, j ), 1 )
238 30 CONTINUE
239 *
240 RETURN
241 *
242 * End of DTBTRS
243 *
subroutine dtbsv(UPLO, TRANS, DIAG, N, K, A, LDA, X, INCX)
DTBSV
Definition: dtbsv.f:191
subroutine xerbla(SRNAME, INFO)
XERBLA
Definition: xerbla.f:62
logical function lsame(CA, CB)
LSAME
Definition: lsame.f:55
Here is the call graph for this function:
Here is the caller graph for this function: | __label__pos | 0.979481 |
SHARE
TWEET
Untitled
a guest Dec 5th, 2018 144 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
1. #! /usr/bin/env python3
2. print("Content-type: text/html\n")
3. import cgi
4. import MySQLdb
5. string = "i211f18_affoster"
6. password = "my+sql=i211f18_affoster"
7. db_con = MySQLdb.connect(host = "db.soic.indiana.edu", port = 3306, user = string, passwd = password, db = string)
8. cursor = db_con.cursor()
9.
10. printing = """<!doctype html>
11. <html>
12. <head>
13. <title>Robot Delivery System</title>
14. </head>
15. <body>
16. <h1>What would you like to have delivered</h1>
17. <form action = "addDelivery.cgi" method = "post">"""
18.
19.
20. try:
21. sql = "select items.itemName from items;"
22. cursor.execute(sql)
23. result = cursor.fetchall()
24. except Exception as e:
25. print("something wrong")
26. else:
27. for row in result:
28. printing += """<input type = "radio" name = "item" value = '""" + row[0] + "'>" + row[0] + "<br>\n"
29.
30. printing += """<h2>Cost: $</h2>
31. <br>
32. <input type = "text" name = "cost">
33. <br>
34. <h2>Delivery Method:</h2>
35. <br>
36. <input type = "radio" name = "method" value = "drone">Flying Drone ($10)
37. <br>
38. <input type = "radio" name = "method" value = "car">Self Driving Car ($20)
39. <br>
40. <input type = "radio" name = "method" value = "robot">Giant Robot ($1000)
41. <br>
42. <button type = "submit">Submit</button>
43. </form>
44. </body>
45. </html>"""
46. print(printing)
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top | __label__pos | 0.999437 |
Chapter 5: Video output
Now video output can be identified. To check for composite video signal, it's convenient to make a probe from an old headphone and resistor. Connect + of headphone to 1kOhm resistor and ground to computer's ground, like you see in the picture below:
Then, poking the video connector, hear the characteristical "wrrrr"-like sound. To avoid complications with RF modulator, try to get to pure video signals if possible.
In fact there are many types of video computer can output. The good thing is that some computers have outputs for few standards, sometimes in one connector. Few of video output types are:
- Composite video (like Amiga 600, Atari XE), can be seen on a TV with composite input, but not always. Sometimes for proprietary CRTs, frequencies may be totally non TV compatible, e.g. in Siemens PC-D computer.
- RF modulator only (like ZX81, ZX Spectrum without modifications) - this is a typical antenna signal, in which picture and sound are modulated into TV frequency. It may be connected to TV, then TV can be tuned to this signal. Quality of this signal is in many cases not satissfying for current conditions.
- RGB (like Amstrad CPC) - special monitor or TV with SCART is needed.
- RGB with Intensity (like in Commodore 128) - requires CGA-friendly monitor, SCART may not work (levels incompatibility). Sometimes they emit signal in TTL format.
- Composite monochrome signal - (e.g. Meritum) monochrome video which can be seen on composite-enabled display.
- Luminance, Composite Sync (Like Robotron PC1715) - requires monitor with such input.
- Luminance/RGB, Horizontal Sync, Vertical Sync - as above.
- YPbPr or YCbCr differential signal (like TI99/4A), you can use Y as grayscale composite.
- RGB with own signal levels (like Orel BK-08), requires to build own converter or modify a TV set.
Many old computers output few of these signals at once, e.g. Robotron KC85 has RF modulator output, but on its edge connector there is composite video and RGB.
In this page [POLISH] there are few connectors and converters (YCbCr to RGB) shown. If in some output there is no signal at all, it means that something is wrong with hardware. Many 8-bit computers just emit display signals independently of CPU.
What if you don't have a monitor at all?
Quite useful thing here is an old TV tuner card in a PCI slot. These cards are now, in a time of digital DVB television, very cheap and allow to capture picture from composite input or TV tuner (so RF modulator output). Better use composite input, as most of these tuners have problems with SECAM color coding when it's emitted by computer's RF modulator (many computers from Eastern block).
Another way to have composite input in your PC monitor is to use a VGA converter called scandoubler (because it doubles the frequency of composite signal). These devices convert composite input to VGA output. They are called "VGABox" or "Grand video console" and are quite expensive.
If you have a computer starting to monitor, BASIC or other OS, you can try to figure out is it working completely.
Chapter 4: Mainboard
Table of contents
Chapter 6: Keyboards
Home
Back to home pagehacks
Back to hacks
MCbx, 2016 | __label__pos | 0.809111 |
javascript
Custom select dropdown using HTML, CSS and Javascript
From the title and image, you already know what we are going to discuss in this article. Yes, it is custom select dropdown using HTML, CSS and Javascript.
Custom select drop down using html css and javascript
Custom select drop down using html css and javascript
List of content
What and Why?
But you may think, Okay, isn’t there already a select element in HTML? Then why are we even thinking of creating a custom select dropdown using javascript?
Yes, there is one. But that one doesn’t do justice to the user experience of your application.
For example, you can’t give it a modern look and feel. And also, the latest frameworks have so much to offer but, our HTML select element is pretty far behind to absorb all those awesomeness.
Hope you are 1% more convinced now? Alrighty then let’s move forward.
Next comes the things that I had to keep in mind while thinking of the element structure.
Look and feel of a custom select dropdown (UI)
If we talk about the look and feel, I have used the below elements:
• A div that looks and behaves like a select element.
• Ul and li elements to render the options.
• A hidden input field to store the actual value of the selected element.
• An outer div that binds all these elements together as one.
• I have used CSS to create the tiny down arrow. Have a look at the .arrow.arrow-down class.
Behavior of a custom select dropdown (UX)
For the element behaviour, I have used pure javascript, no jQuery or any other library. Below are the behaviour things that I have taken care of while developing this element.
• While a user clicks on the select box, a dropdown should open.
• The dropdown must close once a value is selected.
• The selected value must appear in the select box.
• If a user clicks outside the selection area, then the options must close.
File Structure
I have used three files to create this element, layout.html, script.js and style.css. Please have a look at below code and their explanations.
layout.html
<html>
<head>
<script type="text/javascript" src="./script.js"></script>
<link type="text/css" rel="stylesheet" href="./style.css">
</head>
<body>
<div>
<input name="select_value" type="hidden" id="selectedValue">
<div class="display-value" id="displayValue" onclick="toggleOptions(event)">
<span class="value-text" id="valueText">Select</span>
<span class="arrow arrow-down" id="arrowControl"></span>
</div>
<ul tabindex="0" class="select-container" id="selectContainer" onblur="toggleOptions(event)">
<li class="select-option" onclick="selected('Opt1')">Opt1</li>
<li class="select-option" onclick="selected('Opt2')">Opt2</li>
<li class="select-option" onclick="selected('Opt3')">Opt3</li>
</ul>
</div>
</body>
</html>
style.css
.display-value {
height: 39px;
width: 211px;
display: flex;
position: absolute;
border: 2px solid #666;
}
.value-text {
display: flex;
padding-left: 10px;
font-family: sans-serif;
align-items: center;
color: #666;
}
.arrow {
left: 190px;
top: 17px;
position: absolute;
}
.arrow.arrow-up {
width: 0;
height: 0;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-bottom: 6px solid black;
}
.arrow.arrow-down {
width: 0;
height: 0;
border-left: 6px solid transparent;
border-right: 6px solid transparent;
border-top: 6px solid black;
}
.select-container {
width: 211px;
padding: 0px;
position: absolute;
visibility: hidden;
margin: 0px;
height: fit-content;
border: 2px solid #333;
background-color: #fff;
list-style-type: none;
display: block;
}
.select-container:focus {
outline:none;
}
.select-option {
display: none;
height: 40px;
display: flex;
padding-left: 10px;
font-family: sans-serif;
align-items: center;
color: #666;
}
.select-option:hover {
background-color: #eee;
}
script.js
var isOpen = false;
function toggleOptions(e) {
isOpen = !isOpen;
if (isOpen) {
document.getElementById('selectContainer').style.visibility = 'visible';
document.getElementById('selectContainer').focus();
} else {
document.getElementById('selectContainer').blur();
document.getElementById('selectContainer').style.visibility = 'hidden';
}
}
function selected(val) {
document.getElementById('valueText').innerHTML = val;
document.getElementById('selectedValue').val = val;
toggleOptions();
}
Hope you have liked this post. Please comment below if you want to read more similar articles. Thank you!
I have converted it to a reusable select component.
Here is my updated article.
Leave a Comment
+ eighty = eighty nine | __label__pos | 0.913397 |
Skip to content
Webhooks
Webhooks are used to return data when something happens, such as a change in a company in the CVR registry, or the completion of a report.
Whats in the payload?
The payload of the webhook is entirely dependent on the module in which it is used. Refer to the individual documentation below for further information.
Webhook Authentication
If your webhook requires authentication, it can be set up during webhook configuration. If you register the webhook programmatically, the JSON for a webhook config is of the format:
{
"Method": "Header",
"Key": "MyAuthHeader",
"Value": "AuthKey"
}
The following authentication methods are supported:
• Header: A HTTP Header with a header key and a header value.
• BasicAuth: Uses the Authorization header, with key:UserName, value:password
• Kerberos: Uses username and password with optional domain to auth with Kerberos. Key: domain@username and Value:password. Called with ImpersonationLevel: None, Preauthenticate: true, KeepAlive: true and AuthenticationLevel: MutualAuthRequested.
What if my webhook goes down?
If your webhook does not respond with a statuscode in the 200-299 range, we will retry up to 5 times in the next 24 hours, with an increasingly longer delay between each attempt. The first retry attempt will wait 5 minutes, then 30 minutes, then several hours. Each retry might have a little time added to it, in order to space out bursts of calls that may be overloading your webhook.
If your webhook does not respond succesfully to any requests at all in a 24-hour period, it will be disabled and you will receive a warning e-mail.
Available webhooks
Lasso can send various types of data to your webhooks:
• Overvågning: Receive notifications when changes are made in the CVR registry.
• Rapportering: Receive notifications when a report is created. | __label__pos | 0.948361 |
Active Query Builder support area
Fail query validation if custom function is used and not in metadata xml
Avatar
• updated
• Completed
If a user types a UDF in the SQL Editor that is in the database, but isn't in the object tree or metadata, I'd like it to throw an error when they click the refresh/update icon just as if they had typed a table name that isn't there. Is this possible?
Avatar
Andrey Zavyalov, PM
Hello, Marc.
Are you talking about table-valued functions that can be used in the FROM clause or functions in SQL expressions? What you mean by "just as if they had typed a table name that isn't there" - are you talking about the error that is raised when you set the ParsingErrorOnUnknownObjects property to true? An example of what you mean will be very helpful.
Avatar
Marc
Yes, I would like to have it throw an error on unknown objects. I am using
QueryBuilderControl1.QueryBuilder.BehaviorOptions.ParsingErrorOnUnknownObjects = true;
An example would be using your online demo:
Select * From HumanResources.Department
Where someUnwantedFunction(HumanResources.Department.Name) = 1
Avatar
Unfortunately it not possible to setup such behavior with a single property switching. But using Active Query Builder you can get access to any single token of the query AST (abstract syntax tree), and you will know which token is a function, so you can alert the user if unwanted functions are found. I can send you the code sample of doing so if you wish.
Avatar
Here is the code snippet which lists all functions used in query:
using (var syntax = new MSSQLSyntaxProvider())
using (var queryBuilder = new QueryBuilder() {SyntaxProvider = syntax})
{
queryBuilder.SQL = "Select * From HumanResources.Department"+
" Where someUnwantedFunction(HumanResources.Department.Name) = 1";
// get AST (abstract syntax tree) representation
var queryAst = queryBuilder.QueryView.Query.QueryRoot.ResultQueryAST;
// collect all AST nodes in tree var allNodes = new List<AstNodeBase>(); queryAst.GetMyChildrenRecursive(allNodes); // filter function calls
var allFunctionCalls = allNodes.OfType<SQLExpressionFunction>(); // show function names
var sb = new StringBuilder(); foreach (var functionCall in allFunctionCalls) sb.AppendLine(functionCall.Name.QualifiedName);
MessageBox.Show(sb.ToString(), "Used Functions"); }
Avatar
Marc
Is there a way for me to have the control display the same error dialog as with other invalid statements so the user can see 'Unexpected function "someUnwantedFunction" at line X, pos X', i.e. display the error popup and set the qb-ui-editor-refresh-button-label text??
Avatar
Andrey Zavyalov, PM
Hello,
You can call the QB.Web.Application.MessageError(message) method to display an error.
| __label__pos | 0.978789 |
Format not showing correct on web view
I have an app that i have changed the formatting to dark mode and have added some formatting rules to highlight a value based on due date. It works perfect on the app on my iphone but does not show up correctly in the web browser view. Can someone please tell me if it is possible and how to have the web browser mode show in dark mode and have the formatting rules. Thanks
Hi @BKCustoms
Do you have some screen shots to show what is happening? Also have you refreshed your browser?
1 Like
Its happening on mine too:
Clear cached images and files @d.harrier not for the original post*
1 Like
Here is what it looks like in a web browser
here is what it looks like on a mobile device | __label__pos | 0.813746 |
DOC HOME SITE MAP MAN PAGES GNU INFO SEARCH
(gawk.info.gz) Getline
Info Catalog (gawk.info.gz) Multiple Line (gawk.info.gz) Reading Files
Explicit Input with `getline'
=============================
So far we have been getting our input data from `awk''s main input
stream--either the standard input (usually your terminal, sometimes the
output from another program) or from the files specified on the command
line. The `awk' language has a special built-in command called
`getline' that can be used to read input under your explicit control.
The `getline' command is used in several different ways and should
_not_ be used by beginners. The examples that follow the explanation
of the `getline' command include material that has not been covered
yet. Therefore, come back and study the `getline' command _after_ you
have reviewed the rest of this Info file and have a good knowledge of
how `awk' works.
The `getline' command returns one if it finds a record and zero if
it encounters the end of the file. If there is some error in getting a
record, such as a file that cannot be opened, then `getline' returns
-1. In this case, `gawk' sets the variable `ERRNO' to a string
describing the error that occurred.
In the following examples, COMMAND stands for a string value that
represents a shell command.
Menu
* Plain Getline Using `getline' with no arguments.
* Getline/Variable Using `getline' into a variable.
* Getline/File Using `getline' from a file.
* Getline/Variable/File Using `getline' into a variable from a
file.
* Getline/Pipe Using `getline' from a pipe.
* Getline/Variable/Pipe Using `getline' into a variable from a
pipe.
* Getline/Coprocess Using `getline' from a coprocess.
* Getline/Variable/Coprocess Using `getline' into a variable from a
coprocess.
* Getline Notes Important things to know about `getline'.
* Getline Summary Summary of `getline' Variants.
Info Catalog (gawk.info.gz) Multiple Line (gawk.info.gz) Reading Files
automatically generated byinfo2html | __label__pos | 0.9771 |
Logo Search packages:
Sourcecode: jsch version File versions Download package
ProxySOCKS5.java
/* -*-mode:java; c-basic-offset:2; -*- */
/*
Copyright (c) 2002,2003,2004 ymnk, JCraft,Inc. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the distribution.
3. The names of the authors may not be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL JCRAFT,
INC. OR ANY CONTRIBUTORS TO THIS SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
This file depends on following documents,
- RFC 1928 SOCKS Protocol Verseion 5
- RFC 1929 Username/Password Authentication for SOCKS V5.
*/
package com.jcraft.jsch;
import java.io.*;
import java.net.*;
public class ProxySOCKS5 implements Proxy{
private static int DEFAULTPORT=1080;
private String proxy_host;
private int proxy_port;
private String host;
private int port;
private InputStream in;
private OutputStream out;
private Socket socket;
private String user;
private String passwd;
public ProxySOCKS5(String proxy_host){
int port=DEFAULTPORT;
String host=proxy_host;
if(proxy_host.indexOf(':')!=-1){
try{
host=proxy_host.substring(0, proxy_host.indexOf(':'));
port=Integer.parseInt(proxy_host.substring(proxy_host.indexOf(':')+1));
}
catch(Exception e){
}
}
this.proxy_host=host;
this.proxy_port=port;
}
public ProxySOCKS5(String proxy_host, int proxy_port){
this.proxy_host=proxy_host;
this.proxy_port=proxy_port;
}
public void setUserPasswd(String user, String passwd){
this.user=user;
this.passwd=passwd;
}
public void connect(Session session, String host, int port) throws JSchException{
this.host=host;
this.port=port;
try{
SocketFactory socket_factory=session.socket_factory;
if(socket_factory==null){
socket=new Socket(proxy_host, proxy_port);
in=socket.getInputStream();
out=socket.getOutputStream();
}
else{
socket=socket_factory.createSocket(proxy_host, proxy_port);
in=socket_factory.getInputStream(socket);
out=socket_factory.getOutputStream(socket);
}
socket.setTcpNoDelay(true);
byte[] buf=new byte[1024];
int index=0;
/*
+----+----------+----------+
|VER | NMETHODS | METHODS |
+----+----------+----------+
| 1 | 1 | 1 to 255 |
+----+----------+----------+
The VER field is set to X'05' for this version of the protocol. The
NMETHODS field contains the number of method identifier octets that
appear in the METHODS field.
The values currently defined for METHOD are:
o X'00' NO AUTHENTICATION REQUIRED
o X'01' GSSAPI
o X'02' USERNAME/PASSWORD
o X'03' to X'7F' IANA ASSIGNED
o X'80' to X'FE' RESERVED FOR PRIVATE METHODS
o X'FF' NO ACCEPTABLE METHODS
*/
buf[index++]=5;
buf[index++]=2;
buf[index++]=0; // NO AUTHENTICATION REQUIRED
buf[index++]=2; // USERNAME/PASSWORD
out.write(buf, 0, index);
/*
The server selects from one of the methods given in METHODS, and
sends a METHOD selection message:
+----+--------+
|VER | METHOD |
+----+--------+
| 1 | 1 |
+----+--------+
*/
in.read(buf, 0, 2);
boolean check=false;
switch((buf[1])&0xff){
case 0: // NO AUTHENTICATION REQUIRED
check=true;
break;
case 2: // USERNAME/PASSWORD
if(user==null || passwd==null)break;
/*
Once the SOCKS V5 server has started, and the client has selected the
Username/Password Authentication protocol, the Username/Password
subnegotiation begins. This begins with the client producing a
Username/Password request:
+----+------+----------+------+----------+
|VER | ULEN | UNAME | PLEN | PASSWD |
+----+------+----------+------+----------+
| 1 | 1 | 1 to 255 | 1 | 1 to 255 |
+----+------+----------+------+----------+
The VER field contains the current version of the subnegotiation,
which is X'01'. The ULEN field contains the length of the UNAME field
that follows. The UNAME field contains the username as known to the
source operating system. The PLEN field contains the length of the
PASSWD field that follows. The PASSWD field contains the password
association with the given UNAME.
*/
index=0;
buf[index++]=1;
buf[index++]=(byte)(user.length());
System.arraycopy(user.getBytes(), 0, buf, index, user.length());
index+=user.length();
buf[index++]=(byte)(passwd.length());
System.arraycopy(passwd.getBytes(), 0, buf, index, passwd.length());
index+=passwd.length();
out.write(buf, 0, index);
/*
The server verifies the supplied UNAME and PASSWD, and sends the
following response:
+----+--------+
|VER | STATUS |
+----+--------+
| 1 | 1 |
+----+--------+
A STATUS field of X'00' indicates success. If the server returns a
`failure' (STATUS value other than X'00') status, it MUST close the
connection.
*/
in.read(buf, 0, 2);
if(buf[1]==0)
check=true;
break;
default:
}
if(!check){
try{ socket.close(); }
catch(Exception eee){
}
throw new JSchException("fail in SOCKS5 proxy");
}
/*
The SOCKS request is formed as follows:
+----+-----+-------+------+----------+----------+
|VER | CMD | RSV | ATYP | DST.ADDR | DST.PORT |
+----+-----+-------+------+----------+----------+
| 1 | 1 | X'00' | 1 | Variable | 2 |
+----+-----+-------+------+----------+----------+
Where:
o VER protocol version: X'05'
o CMD
o CONNECT X'01'
o BIND X'02'
o UDP ASSOCIATE X'03'
o RSV RESERVED
o ATYP address type of following address
o IP V4 address: X'01'
o DOMAINNAME: X'03'
o IP V6 address: X'04'
o DST.ADDR desired destination address
o DST.PORT desired destination port in network octet
order
*/
index=0;
buf[index++]=5;
buf[index++]=1; // CONNECT
buf[index++]=0;
byte[] hostb=host.getBytes();
int len=hostb.length;
buf[index++]=3; // DOMAINNAME
buf[index++]=(byte)(len);
System.arraycopy(hostb, 0, buf, index, len);
index+=len;
buf[index++]=(byte)(port>>>8);
buf[index++]=(byte)(port&0xff);
out.write(buf, 0, index);
/*
The SOCKS request information is sent by the client as soon as it has
established a connection to the SOCKS server, and completed the
authentication negotiations. The server evaluates the request, and
returns a reply formed as follows:
+----+-----+-------+------+----------+----------+
|VER | REP | RSV | ATYP | BND.ADDR | BND.PORT |
+----+-----+-------+------+----------+----------+
| 1 | 1 | X'00' | 1 | Variable | 2 |
+----+-----+-------+------+----------+----------+
Where:
o VER protocol version: X'05'
o REP Reply field:
o X'00' succeeded
o X'01' general SOCKS server failure
o X'02' connection not allowed by ruleset
o X'03' Network unreachable
o X'04' Host unreachable
o X'05' Connection refused
o X'06' TTL expired
o X'07' Command not supported
o X'08' Address type not supported
o X'09' to X'FF' unassigned
o RSV RESERVED
o ATYP address type of following address
o IP V4 address: X'01'
o DOMAINNAME: X'03'
o IP V6 address: X'04'
o BND.ADDR server bound address
o BND.PORT server bound port in network octet order
*/
in.read(buf, 0, 4);
if(buf[1]!=0){
try{ socket.close(); }
catch(Exception eee){
}
throw new JSchException("ProxySOCKS5: server returns "+buf[1]);
}
switch(buf[3]&0xff){
case 1:
in.read(buf, 0, 6);
break;
case 3:
in.read(buf, 0, 1);
in.read(buf, 0, buf[0]+2);
break;
case 4:
in.read(buf, 0, 18);
break;
default:
}
}
catch(RuntimeException e){
throw e;
}
catch(Exception e){
try{ if(socket!=null)socket.close(); }
catch(Exception eee){
}
throw new JSchException("ProxySOCKS5: "+e.toString());
}
}
public InputStream getInputStream(){ return in; }
public OutputStream getOutputStream(){ return out; }
public void close(){
try{
if(in!=null)in.close();
if(out!=null)out.close();
if(socket!=null)socket.close();
}
catch(Exception e){
}
in=null;
out=null;
socket=null;
}
public static int getDefaultPort(){
return DEFAULTPORT;
}
}
Generated by Doxygen 1.6.0 Back to index | __label__pos | 0.912444 |
th 612 - Understanding the Role of \R in a Script
Understanding the Role of \R in a Script
Posted on
th?q=What Does - Understanding the Role of \R in a Script
As a data analyst or statistician, you might have come across the letter R in various discussions. You may even have heard about R scripts being used to analyze various kinds of data sets. But do you truly understand the role of the R language in scripting? Whether you are a newcomer to R programming or an expert user, this article will help you understand the crucial role of R in scripting and why it matters in data analysis.
Firstly, R is an essential programming language used for analyzing and manipulating statistical data. It was designed specifically for statistical computing and graphics, allowing data analysts and researchers to build powerful tools for data analysis quickly. R helps users to perform complex data analyses, data visualization, and data manipulation in a more comfortable and straightforward manner.
Moreover, understanding the role of R in script writing is vital as R scripts are a core feature of R programming. R scripts allow data analysts to write code that can be saved and run repeatedly, saving time and streamlining their workflow. With R scripts, you can manipulate data sets, import data from files, filter, and summarize data more effectively.
In summary, the R language is critical in scripting for analytical purposes. By using R scripts, data analysts can automate tasks and produce clearer, more precise data reports with ease. If you’re looking to improve your data analysis skills, mastering the R language is an excellent place to start.
th?q=What%20Does%20%22%5CR%22%20Do%20In%20The%20Following%20Script%3F - Understanding the Role of \R in a Script
“What Does “\R” Do In The Following Script?” ~ bbaz
Introduction
R is a programming language that has now become one of the most popular languages in statistics and data science. It is an open source language commonly used for statistical analysis and visualization. The understanding of R scripts is very important for any data science professional or anyone interested in performing statistical analysis. In this article, we would be discussing the role of R in a script and how the language makes it easier to perform analysis and visualization.
The Function of R
The primary function of R is to facilitate statistical analysis and visualization. It’s a free tool that provides a wide variety of statistical techniques, such as linear and nonlinear modeling, time-series analysis, clustering, and classical statistical tests. With its large repository of add-on packages (also known as libraries), R can perform complex statistical analyses on datasets with ease.
Why Use R
The advantages of using R are its ability to handle big data and produce high-quality visualizations quickly. Its statistical computing capabilities make it well suited for fields like econometrics, finance, and bioinformatics where statistical analysis is crucial. Its graphical output capabilities provide consistently high-quality graphs that are suitable for scientific and business presentations.
Data Handling with R
In a data science project, data handling is a critical part of the process. In R, data sets can be imported from various sources such as CSV, Excel, SQL databases, and other statistical packages. Cleaning data is also easier in R since missing data can be handled easily, and outliers can be identified and transformed according to the needs of the analysis.
Plotting Graphs with R
R makes it easy for analysts to create effective visualizations through its flexible and customizable graphics capabilities. The library ggplot2 provides an extensive set of tools to create highly customizable plots, allowing users to adjust elements such as colors, size, and shape to fit their specific needs.
Comparison with Python
Python is another popular language for data science and statistical analysis. Similar to R, it can handle big datasets effectively and provide high-quality visualizations. However, the primary difference lies in the fact that Python is not specifically designed for statistical analysis but is more of a multi-purpose language. R on the other hand is primarily focused on statistical computing and analysis.
R Python
Open source Open source
Focused on statistical computing and analysis Multi-purpose language
Packages built specifically for statistical techniques Less statistical packages compared to R
Excellent graphical output capabilities Graphical output is not as extensive as R
Conclusion
In conclusion, R is an efficient and effective tool for statistical computing and visualization. Its flexibility, graphics capabilities and comprehensive set of packages make it well suited for data science projects. The role of R in a script cannot be overemphasized, and by highlighting some of its benefits, we hope that more people can appreciate the power and potential of this open-source programming language in statistical computing and visualization.
References
• DataCamp. (2021). Why You Should Learn R in 2021. [online] Available at: https://www.datacamp.com/community/blog/why-you-should-learn-r-in-2021 [Accessed 30 Nov. 2021].
• Leeper, T. (2017). Why R is Hard(er than it Needs to be). [online] Available at: https://peerj.com/preprints/3188/ [Accessed 30 Nov. 2021].
• Prasad, D. (2021). Python Vs R – How to Choose the Right One for Data Science Projects? [online] KDnuggets. Available at: https://www.kdnuggets.com/2020/05/python-vs-r-right-data-science-project.html [Accessed 30 Nov. 2021].
Thank you for visiting our blog and taking the time to learn about the role of R in scripting! We hope that we have been able to provide you with a comprehensive overview of this important programming language and how it can be used to streamline your data analysis processes. Whether you are a seasoned programmer or just starting out in the field, understanding the power of R can give you an edge in your work and help you achieve your goals more efficiently.
As we discussed in our article, R is an open-source language that is widely used for statistical analysis, data visualization, and machine learning. It has a vast library of built-in functions and packages that make it easy to manipulate data, perform complex calculations, and generate high-quality graphics. Whether you are working with large datasets or exploring new insights, R offers a flexible and efficient platform that can help you achieve your goals.
In conclusion, we hope that our article has helped you gain a deeper understanding of the role of R in scripting and how it can be used to enhance your work. We encourage you to continue exploring this powerful language and to share your experiences and insights with others in the programming community. Thank you again for visiting and we look forward to seeing you again soon!
People also ask about Understanding the Role of R in a Script:
1. What is R and why is it important in scripting?
2. R is an open-source programming language that is widely used for statistical computing and data analysis. It is important in scripting because it provides a range of functions and packages for data manipulation, visualization, modeling, and inference.
3. What are the benefits of using R in scripting?
4. Using R in scripting offers several benefits such as its ability to handle large datasets, its flexibility and versatility in performing statistical analyses, and its ability to generate high-quality graphics and visualizations.
5. What are some common uses of R in scripting?
6. R is commonly used in scripting for data cleaning and preprocessing, exploratory data analysis, statistical modeling and inference, machine learning, and creating visualizations and reports.
7. What are some popular packages in R for scripting?
8. Some popular packages in R for scripting include ggplot2 for creating high-quality graphics, dplyr for data manipulation, tidyr for data tidying, and caret for machine learning.
9. How can I learn more about using R in scripting?
10. There are many resources available online for learning R in scripting, including tutorials, books, and online courses. Some popular resources include the RStudio website, the RDocumentation website, and the DataCamp website. | __label__pos | 0.988546 |
In WCF, ServiceContract attribute affect the behavior of both client and server, while ServiceBehavior only affect the behavior of server. ServiceContract can apply both to interface and class, but ServiceBehavior can only apply to class implementation. ServiceContract affect the wsdl emitted, but ServiceBehavior will not affect wsdl emitted.
public enum SessionMode
{
Allowed,
Required,
NotAllowed
}
[AttributeUsage(AttributeTargets.Interface|AttributeTargets.Class,
Inherited=false)]
public sealed class ServiceContractAttribute : Attribute
{
public SessionMode SessionMode
{get;set;}
//More members
}
[AttributeUsage(AttributeTargets.Class)]
public sealed class ServiceBehaviorAttribute : Attribute, IServiceBehavior
{
}
// Summary:
// Specifies the number of service instances available for handling calls that
// are contained in incoming messages.
public enum InstanceContextMode
{
// Summary:
// A new System.ServiceModel.InstanceContext object is created for each session.
PerSession = 0,
//
// Summary:
// A new System.ServiceModel.InstanceContext object is created prior to and
// recycled subsequent to each call. If the channel does not create a session
// this value behaves as if it were System.ServiceModel.InstanceContextMode.PerCall.
PerCall = 1,
//
// Summary:
// Only one System.ServiceModel.InstanceContext object is used for all incoming
// calls and is not recycled subsequent to the calls. If a service object does
// not exist, one is created.
Single = 2,
}
InstanceContextMode is a property of ServiceBehavior attribute, it affect server only. Its default value is PerSession.PerSession, but PerCall can get the best scalability, which is generally recommended. But PerSession is not compatible with transport protocol binding like basicHttpBinding. And the implementation requires to follow IDisposable pattern and Session retore pattern to support PerCall behavior.
SessionMode mode is a property of ServiceContract, it affect both the client. It is default value is "Allowed". It tells the client whether it should keep a session with server. When you create proxy at client side, that proxy will create a session in first call. If you create another proxy, that will create a new session. In order to correlate all messages from a particular client to a particular instance, WCF needs to be able to identify the client. One way of doing that is to rely on a transport-level session; that is, a continuous connection at the transport level, such as the one maintained by the TCP and IPC protocols. As a result, when using the NetTcpBinding or the NetNamedPipeBinding, WCF associates that connection with the client. The situation is more complex when it comes to the connectionless nature of the HTTP protocol. Conceptually, each message over HTTP reaches the services on a new connection. Consequently, you cannot maintain a transport-level session over the BasicHttpBinding. The WS binding, on the other hand, is capable of emulating a transport-level session by including a logical session ID in the message headers that uniquely identifies the client. In fact, the WSHttpBinding will emulate a transport session whenever security or reliable messaging is enabled.
When we implement our service, we can use different combination of SessionMode(client), InstanceContextMode(server), and transporation binding. SessionMode and InstanceContextMode has no configuration confict, which means any SessionMode can go with any InstanceContextMode. But there are some design conflict. For example, SessionMode.NotAllowed does not go with InstanceContextMode.PerSession very well. To maintain a instance per session, client should support session as well. If client does not allowed session, every service call is treated as new session. But it will not caused configuration error. To support SessionMode.Required, binding can not be basicHttpBinding. The combination of SessionMode.Required and basicHttpBinding will generate a configuration error. InstanceContextMode.PerSession can works with basicHttpBinding, but every service call will treated as new session. | __label__pos | 0.915144 |
Activity critical mass dating site
Shepard refers to the original Cerberus goal of giving humanity a fighting chance as something EDI can get behind on. And who, or what, is the Alliance?
These signals are used to look inside the planet to a depth of many kilometers in order to locate underground munitions, minerals and tunnels. In comparison to the geth, her singular personality allows her to develop preferences, thus keeping her from devaluing the lives onboard the Normandy.
She asks Shepard to resolve her existential crisis, and the Commander replies that she doesn't have to hold to the same standards as organics.
Students will apply computer technology to a course-long business case. An insect lands, and the web's vibrations alert the spider to possible prey. For example, ozone, nitrogen, etc. The arrests and indictments are working their way up to some of the very highest-level people — who have been sitting on these UFO secrets for 70 years.
The problem is that the frequency needed for earth-penetrating radiation is within the frequency range most cited for disruption of human mental functions. Thus Tesla's resonance effects can control enormous energies by tiny triggering signals.
Electronic Rain From The Sky They have published papers about electron precipitation from the magnetosphere the outer belts of charged particles which stream toward Earth's magnetic poles caused by man-made very low frequency electromagnetic waves.
She succeeds in recovering Vendetta, and proceeds to listen to the VI's revelations before it's interrupted by a blast. They could make enormous profits by beaming electrical power from a powerhouse in the gas fields to the consumer without wires.
The Eastlund ionospheric heater was different; the radio frequency RF radiation was concentrated and focused to a point in the ionosphere. President Carter and J.
Section Amends FISA, allowing the government to order the collection of "tangible things" that aid in an terrorism or espionage investigation. Some of it also appears in The Ascension Mysteries.
These changes further result in myocardial cell damage in the lining of the heart, leading to scar tissue and thickened walls. Congress' subcommittee hearings on Oceans and International Environment looked into military weather and climate modification conducted in the early 's.
She does not blame either Joker or Shepard for their feelings, but merely states that they choose that which they find familiar and that they are not alone in that mindset, possibly alluding to the geth and their decision to serve the Reapers.
The author of the government report refers to an earlier Air Force document about the uses of radio frequency radiation in combat situations. Much more of it will be covered, as well as how it ties in with my own bizarre experiences, in my new book Awakening in the Dream, due in August.
In addition, students will learn how to work with tables, mail merge, templates, and desktop publishing, as well as how to collaborate with others, and create web pages. Additionally, our half-hour-long Gaia show Cosmic Disclosure has been running weekly now for two and a half years.
Too much exercise may cause a woman to cease menstruation, a symptom known as amenorrhea. Deacon appeared briefly in and then went back into hiding. Educators have permission to reprint articles for classroom use; other users, please contact editor actionbioscience.
If Shepard tells her she herself would know the difference, EDI realizes the technique could be applied to any goal she sets. MacDonald science advisor to U. If Shepard warns her not to think like a Reaper, EDI refers to their lifespan of "fifty thousand to thirty-seven million years" as a "very successful model.
She says that the krogan have been demilitarized and thus have no warships, which would require transporting them by turian or civilian ships to carry them into battle. If Mordin is present on the Normandy, EDI tells Shepard about a conversation with him about the salarian equivalent of transhumans.
The scheme worked all round the world, without fail. Shepard can ask EDI about her new body's capabilities and advantages.Our understanding of the shape and pattern of the history of life depends on the accuracy of fossils and dating methods.
Some critics, particularly religious fundamentalists, argue that neither fossils nor dating can be trusted, and that their interpretations are better. When Edward Snowden met journalists in his cramped room in Hong Kong's Mira hotel in June, his mission was ambitious.
Amid the clutter of laundry, meal trays and his four laptops, he wanted to.
NSA files decoded: Edward Snowden's surveillance revelations explained
Mass Effect 2 Edit. EDI is a Quantum Blue Box type AI that functions as the electronic warfare defense for the Normandy SR Because of the potential danger of a rogue AI, she has been given behavioral blocks and cannot interface with the ship's systems.
HAARP is the acronym many people recognize, it is an "ionosphere heater" facility in Alaska. Mainstream media and the military industrial complex tried to convince the public that HAARP was going to be completely dismantled by the summer ofbut did this happen?
The essential tech news of the moment. Technology's news site of record. Not for dummies. SEKRET MACHINES.
Toxic oceans drove mass extinction 200 million years ago
The apparent mis-spelling of the word “secret” in the above tweet is a nod to DeLonge’s co-authored, two-part book series entitled Sekret Machines. With the inclusion of the letter K, it becomes a German word.
Download
Activity critical mass dating site
Rated 3/5 based on 10 review | __label__pos | 0.505237 |
Arcade & Calculate field with text and incrementing number with a starting number and an interval
954
20
12-15-2021 04:09 AM
AGP
by
Occasional Contributor
I have Python calculate field expression (.cal file) that does this but I'm trying to migrate it to Arcade.
It's not working. The number part is not incrementing and I guess it has to do with me not being able of defining 'rec' as a global variable.
This is the Python expression. How do I migrate the 'global rec' line to Arcade?
#Params
val_counter = 2498
prefix = 'PP_'
interval = 1
# -------------------------------------------
# Function
rec=0
def SetIDcode(val_counter, prefix, interval):
global rec
if (rec == 0):
rec = val_counter
else:
rec += interval
return (prefix+ str(rec))
0 Kudos
20 Replies
jcarlson
MVP Honored Contributor
Here's the equivalent of your function in Arcade:
var rec = 0
function SetIDcode(val_counter, prefix, interval){
if (rec == 0){
rec = val_counter
} else {
rec += interval
}
return prefix + rec
}
Here's me testing it with the sample parameters you gave:
jcarlson_0-1639575923687.png
Can you explain a bit more about how you use this, though? Is the rec variable always going to be 0, or are there other parts of the expression that alter it?
- Josh Carlson
Kendall County GIS
0 Kudos
AGP
by
Occasional Contributor
The rec variable is 0 for the first feature, so the returned valued is prefix + val_counter (PP_2498).
But then the rec varaible should get the value in val_counter for the second feature returning prefix + val_counter + interval (PP_2499) and incrementing by interval for each next feature (PP_2500, 2501,...).
Your function (mine was like yours) returns PP_2498 for every feature.
0 Kudos
jcarlson
MVP Honored Contributor
I see. That will only work for an iterative loop, not in the Field Calculate profile. When writing a field calculation in Arcade, you have to imagine that you're already in the loop, as the expression will be evaluated for every feature.
In Arcade, we can access and work with the other values in the layer, so you've got some options. Is the code stored only as a string, or is there some way to access the numeric val_counter without the prefix?
Also, what values are in this field right now? Are they null? Does the val_counter correspond to the number of records in the layer?
- Josh Carlson
Kendall County GIS
0 Kudos
AGP
by
Occasional Contributor
The user inputs the val_counter value according to their needs, as well as the prefix and interval values.
I guess interval will always be 1 but they are given the option to decide.
0 Kudos
jcarlson
MVP Honored Contributor
Are you sure the Arcade field calculator is the right option for this? You may be better off my making your python script into a GP tool.
- Josh Carlson
Kendall County GIS
0 Kudos
AGP
by
Occasional Contributor
The python field calculator is a good option actually. We wanted to use the existing tools in ArcGIS Pro as much as possible and also try to use Arcade as much as possible, but I see python is still the way to go for some processing. We are still evaluating all the geoprocessing needs of our users and maybe will consider using a custom python toolbox. We'll see.
0 Kudos
jcarlson
MVP Honored Contributor
Could you build this into a model, perhaps? Then you could still be using a field calculation with the expression baked in, but expose the layer and field as user-specified parameters.
- Josh Carlson
Kendall County GIS
0 Kudos
JoeBorgione
MVP Esteemed Contributor
What if you use an attribute rule that grabs a the next value from a geodatabase sequence?
That should just about do it....
0 Kudos
AGP
by
Occasional Contributor
I thought of the possibility of using Batch calculation rules so users would execute the rules whenever they need it. We should just publish our feature services with the validation capability enabled and create a database sequence (if the db admin approves).
The problem here is that the user decides the layer and field they will populate so attribute rules are not an option. Using a calculate field expression is more convenient here but we wanted to use Arcade instead of Python.
0 Kudos | __label__pos | 0.727475 |
Adds columns from a set of data frames, creating all combinations of their rows
cross_join(..., copy = FALSE)
Arguments
...
Data frames or a list of data frames -- including data frame extensions (e.g. tibbles) and lazy data frames (e.g. from dbplyr or dtplyr)
copy
If inputs are not from the same data source, and copy is TRUE, then they will be copied into the same src as the first input. This allows you to join tables across srcs, but it is a potentially expensive operation so you must opt into it.
Value
An object of the same type as the first input. The order of the rows and columns of the first input is preserved as much as possible. The output has the following properties:
• Rows from each input will be duplicated.
• Output columns include all columns from each input. If columns have the same name, suffixes are added to disambiguate.
• Groups are taken from the first input.
See also
cross_list() to find combinations of elements of vectors and lists.
Examples
fruits <- tibble::tibble( fruit = c("apple", "banana", "cantaloupe"), color = c("red", "yellow", "orange") ) desserts <- tibble::tibble( dessert = c("cupcake", "muffin", "streudel"), makes = c(8, 6, 1) ) cross_join(fruits, desserts)
#> # A tibble: 9 x 4 #> fruit color dessert makes #> <chr> <chr> <chr> <dbl> #> 1 apple red cupcake 8 #> 2 apple red muffin 6 #> 3 apple red streudel 1 #> 4 banana yellow cupcake 8 #> 5 banana yellow muffin 6 #> 6 banana yellow streudel 1 #> 7 cantaloupe orange cupcake 8 #> 8 cantaloupe orange muffin 6 #> 9 cantaloupe orange streudel 1
cross_join(list(fruits, desserts))
#> # A tibble: 9 x 4 #> fruit color dessert makes #> <chr> <chr> <chr> <dbl> #> 1 apple red cupcake 8 #> 2 apple red muffin 6 #> 3 apple red streudel 1 #> 4 banana yellow cupcake 8 #> 5 banana yellow muffin 6 #> 6 banana yellow streudel 1 #> 7 cantaloupe orange cupcake 8 #> 8 cantaloupe orange muffin 6 #> 9 cantaloupe orange streudel 1
cross_join(rep(list(fruits), 3))
#> # A tibble: 27 x 6 #> fruit.1 color.1 fruit.2 color.2 fruit.3 color.3 #> <chr> <chr> <chr> <chr> <chr> <chr> #> 1 apple red apple red apple red #> 2 apple red apple red banana yellow #> 3 apple red apple red cantaloupe orange #> 4 apple red banana yellow apple red #> 5 apple red banana yellow banana yellow #> 6 apple red banana yellow cantaloupe orange #> 7 apple red cantaloupe orange apple red #> 8 apple red cantaloupe orange banana yellow #> 9 apple red cantaloupe orange cantaloupe orange #> 10 banana yellow apple red apple red #> # … with 17 more rows | __label__pos | 0.601207 |
Switch branches/tags
Nothing to show
Find file History
Pull request Compare This branch is 3 commits ahead, 1169 commits behind chef-boneyard:master.
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
..
Failed to load latest commit information.
recipes
templates/default
README.md
metadata.json
metadata.rb
README.md
Application cookbook
This cookbook is initially designed to be able to describe and deploy web applications. Currently supported:
• Rails
• Java
Other application stacks (PHP, DJango, etc) will be supported as new recipes at a later date.
This cookbook aims to provide primitives to install/deploy any kind of application driven entirely by data defined in an abstract way through a data bag.
Requirements
Chef 0.8 or higher required.
The following Opscode cookbooks are dependencies:
• runit
• unicorn
• apache2
• tomcat
The following are also dependencies, though the recipes are considered deprecated, may be useful for future development.
• ruby_enterprise
• passenger_enterprise
Recipes
The application cookbook contains the following recipes.
default
Searches the apps data bag and checks that a server role in the app exists on this node, adds the app to the run state and uses the role for the app to locate the recipes that need to be used. The recipes listed in the "type" part of the data bag are included by this recipe, so only the "application" recipe needs to be in the node or role run_list.
See below regarding the application data bag structure.
java_webapp
Using the node's run_state that contains the current application in the search, this recipe will install required packages, set up the deployment scaffolding, create the context configuration for the servlet container and then performs a remote_file deploy.
The servlet container context configuration (context.xml) exposes the following JNDI resources which can be referenced by the webapp's deployment descriptor (web.xml):
• A JDBC datasource for all databases in the node's current app_environment. The datasource uses the information (including JDBC driver) specified in the data bag item for the application.
• An Environment entry that matches the node's current app_environment attribute value. This is useful for loading environment specific properties files in the web application.
This recipe assumes some sort of build process, such as Maven or a Continuous Integration server like Hudson, will create a deployable artifact and make it available for download via HTTP (such as S3).
passenger_apache2
Requires apache2 and passenger_apache2 cookbooks. The recipe[apache2] entry should come before recipe[application] in the run list.
"run_list": [
"recipe[apache2]",
"recipe[application]"
],
Sets up a passenger vhost template for the application using the apache2 cookbook's web_app definition. Use this with the rails recipe, in the list of recipes for a specific application type. See data bag example below.
rails
Using the node's run_state that contains the current application in the search, this recipe will install required packages and gems, set up the deployment scaffolding, creates database and memcached configurations if required and then performs a revision-based deploy.
This recipe can be used on nodes that are going to run the application, or on nodes that need to have the application code checkout available such as supporting utility nodes or a configured load balancer that needs static assets stored in the application repository.
For Gem Bundler: include bundler or bundler08 in the gems list. bundle install or gem bundle will be run before migrations.
For config.gem in environment: rake gems:install RAILS_ENV=<node environment> will be run when a Gem Bundler command is not.
In order to manage running database migrations (rake db:migrate), you can use a role that sets the run_migrations attribute for the application (my_app, below) in the correct environment (production, below). Note the data bag item needs to have migrate set to true. See the data bag example below.
{
"name": "my_app_run_migrations",
"description": "Run db:migrate on demand for my_app",
"json_class": "Chef::Role",
"default_attributes": {
},
"override_attributes": {
"apps": {
"my_app": {
"production": {
"run_migrations": true
}
}
}
},
"chef_type": "role",
"run_list": [
]
}
Simply apply this role to the node's run list when it is time to run migrations, and the recipe will remove the role when done.
tomcat
Requires tomcat cookbook.
Tomcat is installed, default attributes are set for the node and the app specific context.xml is symlinked over to Tomcat's context directory as the root context (ROOT.xml).
unicorn
Requires unicorn cookbook.
Unicorn is installed, default attributes are set for the node and an app specific unicorn config and runit service are created.
Deprecated Recipes
The following recipes are deprecated and have been removed from the cookbook. To retrieve an older version, reference commit 4396ce6.
passenger-nginx rails_nginx_ree_passenger
Application Data Bag (Rail's version)
The applications data bag expects certain values in order to configure parts of the recipe. Below is a paste of the JSON, where the value is a description of the key. Use your own values, as required. Note that this data bag is also used by the database cookbook, so it will contain database information as well. Items that may be ambiguous have an example.
The application used in examples is named my_app and the environment is production. Most top-level keys are Arrays, and each top-level key has an entry that describes what it is for, followed by the example entries. Entries that are hashes themselves will have the description in the value.
Note about "type": the recipes listed in the "type" will be included in the run list via include_recipe in the application default recipe based on the type matching one of the server_roles values.
Note about databases, the data specified will be rendered as the database.yml file. In the database cookbook, this information is also used to set up privileges for the application user, and create the databases.
Note about gems and packages, the version is optional. If specified, the version will be passed as a parameter to the resource. Otherwise it will use the latest available version per the default :install action for the package provider.
{
"id": "my_app",
"server_roles": [
"application specific role(s), typically the name of the app, e.g., my_app",
"my_app"
],
"type": {
"my_app": [
"recipes in this application cookbook to run for this role",
"rails",
"unicorn"
]
},
"memcached_role": [
"name of the role used for the app-specific memcached server",
"my_app_memcached"
],
"database_slave_role": [
"name of the role used by database slaves, typically named after the app, 'my_app_database_slave'",
"my_app_database_slave"
],
"database_master_role": [
"name of the role used by database master, typically named after the app 'my_app_database_master'",
"my_app_database_master"
],
"repository": "[email protected]:company/my_app.git",
"revision": {
"production": "commit hash, branch or tag to deploy"
},
"force": {
"production": "true or false w/o quotes to force deployment, see the rails.rb recipe"
},
"migrate": {
"production": "true or false boolean to force migration, see rails.rb recipe"
},
"databases": {
"production": {
"reconnect": "true",
"encoding": "utf8",
"username": "db_user",
"adapter": "mysql",
"password": "awesome_password",
"database": "db_name_production"
}
},
"mysql_root_password": {
"production": "password for the root user in mysql"
},
"mysql_debian_password": {
"production": "password for the debian-sys-maint user on ubuntu/debian"
},
"mysql_repl_password": {
"production": "password for the 'repl' user for replication."
},
"snapshots_to_keep": {
"production": "if using EBS, integer of the number of snapshots we're going to keep for this environment."
},
"deploy_key": "SSH private key used to deploy from a private git repository",
"deploy_to": "path to deploy, e.g. /srv/my_app",
"owner": "owner for the application files when deployed",
"group": "group for the application files when deployed",
"packages": {
"package_name": "specific packages required for installation at the OS level to run the app like libraries and specific version, e.g.",
"curl": "7.19.5-1ubuntu2"
},
"gems": {
"gem_name": "specific gems required for installation to run the application, and if a specific version is required, e.g.",
"rails": "2.3.5"
},
"memcached": {
"production": {
"namespace": "specify the memcache namespace, ie my_app_environment"
}
}
}
Application Data Bag (Java webapp version)
The applications data bag expects certain values in order to configure parts of the recipe. Below is a paste of the JSON, where the value is a description of the key. Use your own values, as required. Note that this data bag is also used by the database cookbook, so it will contain database information as well. Items that may be ambiguous have an example.
The application used in examples is named my_app and the environment is production. Most top-level keys are Arrays, and each top-level key has an entry that describes what it is for, followed by the example entries. Entries that are hashes themselves will have the description in the value.
Note about "type": the recipes listed in the "type" will be included in the run list via include_recipe in the application default recipe based on the type matching one of the server_roles values.
Note about databases, the data specified will be rendered as JNDI Datasource Resources in the servlet container context confiruation (context.xml) file. In the database cookbook, this information is also used to set up privileges for the application user, and create the databases.
Note about packages, the version is optional. If specified, the version will be passed as a parameter to the resource. Otherwise it will use the latest available version per the default :install action for the package provider.
{
"id": "my_app",
"server_roles": [
"application specific role(s), typically the name of the app, e.g., my_app",
"my_app"
],
"type": {
"my_app": [
"recipes in this application cookbook to run for this role",
"java_webapp",
"tomcat"
]
},
"database_slave_role": [
"name of the role used by database slaves, typically named after the app, 'my_app_database_slave'",
"my_app_database_slave"
],
"database_master_role": [
"name of the role used by database master, typically named after the app 'my_app_database_master'",
"my_app_database_master"
],
"wars": {
"production": {
"source": "source url of WAR file to deploy",
"checksum": "SHA256 (or portion thereof) of the WAR file to deploy"
}
},
"databases": {
"production": {
"max_active": "100",
"max_idle": "30",
"max_wait": "10000",
"username": "db_user",
"adapter": "mysql",
"driver": "com.mysql.jdbc.Driver",
"port": "3306",
"password": "awesome_password",
"database": "db_name_production"
}
},
"mysql_root_password": {
"production": "password for the root user in mysql"
},
"mysql_debian_password": {
"production": "password for the debian-sys-maint user on ubuntu/debian"
},
"mysql_repl_password": {
"production": "password for the 'repl' user for replication."
},
"snapshots_to_keep": {
"production": "if using EBS, integer of the number of snapshots we're going to keep for this environment."
},
"deploy_to": "path to deploy, e.g. /srv/my_app",
"owner": "owner for the application files when deployed",
"group": "group for the application files when deployed",
"packages": {
"package_name": "specific packages required for installation at the OS level to run the app like libraries and specific version, e.g.",
"curl": "7.19.5-1ubuntu2"
}
}
Usage
To use the application cookbook, we recommend creating a role named after the application, e.g. my_app. This role should match one of the server_roles entries, that will correspond to a type entry, in the databag. Create a Ruby DSL role in your chef-repo, or create the role directly with knife.
% knife role show my_app
{
"name": "my_app",
"chef_type": "role",
"json_class": "Chef::Role",
"default_attributes": {
},
"description": "",
"run_list": [
"recipe[application]"
],
"override_attributes": {
}
}
Also recommended is a cookbook named after the application, e.g. my_app, for additional application specific setup such as other config files for queues, search engines and other components of your application. The my_app recipe can be used in the run list of the role, if it includes the application recipe.
You should also have a role for the environment(s) you wish to use this cookbook. Similar to the role above, create the Ruby DSL file in chef-repo, or create with knife directly.
% knife role show production
{
"name": "production",
"chef_type": "role",
"json_class": "Chef::Role",
"default_attributes": {
"app_environment": "production"
},
"description": "production environment role",
"run_list": [
],
"override_attributes": {
}
}
This role uses a default attribute so nodes can be moved into other environments on the fly simply by modifying their node object directly on the Chef Server.
License and Author
Author:: Adam Jacob ([email protected]) Author:: Joshua Timberman ([email protected]) Author:: Seth Chisamore ([email protected])
Copyright 2009-2010, Opscode, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. | __label__pos | 0.638629 |
NavigationContentFooter
Jump toSuggest an edit
Create a serverless architecture for handling large messages using Scaleway's NATS, Serverless Functions, and Object Storage.
Reviewed on 22 January 2024Published on 22 January 2024
• message
• nats
• serverless
• serverless-functions
• functions
• serverless-triggers
• triggers
• storage
• object-storage
• terraform
• large-messages
• big-data
• tutorial
Introduction
In this tutorial, we will build a simple architecture to store and automatically convert images to PDF. The focus is on transferring large messages using a messaging service, specifically the Scaleway Messaging and Queuing NATS server. Our setup involves using the Object Storage service for image storage and the Serverless Functions service for conversion.
We show how to provision all the required Scaleway resources via Terraform, but you can also use the console, the API or one of our other supported developer tools.
You can retrieve the full source code in this repository, so you can choose to either jump straight into the code, or else follow along with the step-by-step explanation below to create the architecture yourself.
Before you start
To complete the actions presented below, you must have:
• A Scaleway account logged into the console
• Owner status or IAM permissions allowing you to perform actions in the intended Organization
• Installed Terraform on your local machine
• Set up authentication for the Terraform provider
• Installed Docker on your local machine
• Installed NATS CLI on your local machine
• AWS CLI configured with Scaleway credentials
Architecture
This tutorial’s architecture is very simple, consisting of two main components:
• A producer implemented as a shell script responsible for uploading an image to the Object Storage bucket and sending a message to the NATS server.
• A consumer implemented as a serverless Python function designed to receive the message, parse it, extract the image URL, download it from the bucket, convert it to a PDF, and then re-upload the resulting PDF.
Three essential services are required to ensure everything is working together:
• An Object Storage bucket for storing the image file.
• A Messaging and Queuing NATS server responsible for receiving and dispatching messages sent by our producer.
• A triggering mechanism in NATS that forwards the message to our consumer.
Prepare the infrastructure
1. Create a main.tf file, which we will use to provision all our Scaleway resources and infrastructure. Paste the following code to import the necessary providers.
Tip
Remember that you can refer to the code repository to check all code files.
terraform {
required_providers {
scaleway = {
source = "scaleway/scaleway"
}
null = {
source = "hashicorp/null"
}
random = {
source = "hashicorp/random"
}
archive = {
source = "hashicorp/archive"
}
}
required_version = ">= 0.13"
}
The Scaleway provider is needed, but also three providers from HashiCorp that we will use later in the tutorial.
2. Include two variables to enable the secure passage of your Scaleway credentials. Then initialize the Scaleway provider in the fr-par-1 region.
variable "scw_access_key_id" {
type = string
sensitive = true
}
variable "scw_secret_access_key" {
type = string
sensitive = true
}
provider "scaleway" {
zone = "fr-par-1"
}
3. Create a terraform.tfvars file and add your Scaleway access key and access key id to it.
scw_access_key_id = "YOUR_SCW_SECRET_KEY_ID"
scw_secret_access_key = "YOUR_SCW_SECRET_KEY"
4. Continuing in the main.tf file, add the following Terraform code to create an Object Storage bucket that will be used for storing your images.
resource "random_id" "bucket" {
byte_length = 8
}
resource "scaleway_object_bucket" "large_messages" {
name = "large-messages-${random_id.bucket.hex}"
}
resource "scaleway_object_bucket_acl" "large_messages" {
bucket = scaleway_object_bucket.large_messages.id
acl = "private"
}
output "bucket_name" {
value = scaleway_object_bucket.large_messages.name
description = "Bucket name to use with the producer script"
}
In this code, the resource random_id.bucket generates a random ID, which is then passed to the object bucket to ensure its uniqueness. Additionally, a scaleway_object_bucket_acl ACL is applied to the bucket, setting it to private and outputting the bucket name for use in your producer.
5. Add these resources to create a NATS account and your NATS credentials file:
resource "scaleway_mnq_nats_account" "large_messages" {
name = "nats-acc-large-messages"
}
resource "scaleway_mnq_nats_credentials" "large_messages" {
name = "nats-large-messages-creds"
account_id = scaleway_mnq_nats_account.large_messages.id
}
resource "local_file" "nats_credential" {
content = scaleway_mnq_nats_credentials.large_messages.file
filename = "large-messages.creds"
file_permission = 644
}
output "nats_url" {
value = scaleway_mnq_nats_account.large_messages.endpoint
description = "NATS url to use with the producer script"
}
We also output the NATS server URL.
6. Run terraform init and terraform apply to create the resources in your Scaleway account.
Create the producer
As mentioned earlier, the producer will be implemented as a straightforward shell script.
1. Create a file named upload_img.sh. Inside it, define two variables using Terraform commands to retrieve the bucket name and the NATS URL.
SCW_BUCKET="$(terraform output bucket_name)"
SCW_NATS_URL="$(terraform output nats_url)"
2. Configure the NATS CLI with the NATS URL and the credentials file.
nats context save large-messages --server=$SCW_NATS_URL --creds=./large-messages.creds
nats context select large-messages
Our script takes the file path that we want to upload as the first parameter.
To upload the file, we will use the AWS CLI configured with the Scaleway endpoint and credentials, because Scaleway Object storage is fully compliant with S3.
3. Pass the path to the AWS CLI command as follows:
aws s3 cp $1 s3://$SCW_BUCKET
4. Paste the following command into the script to have it send a message to your NATS server, including the name of the uploaded file.
nats pub large-messages $(basename $1)
Create the consumer
We continue using the Scaleway ecosystem and deploy the consumer using a Serverless Function in Python.
1. Create a folder function. Inside the folder, create another folder handler with a file named large_messages.py.
2. In addition to the handler folder, create a requirements.txt file. Your directory structure should resemble the following: You should have a structure like the following:
function/
├── handler/
│ └── large_messages.py
└── requirements.txt
3. In the requirements.txt add:
boto3
img2pdf
Within the serverless function, we use two Python libraries. First, boto3 is configured similarly to AWS CLI, enabling the download and upload of files to the bucket. Second, img2pdf is used to convert our image into a PDF format.
4. Next create the code of your function. In the file large_messages.py, import the libraries that we need and create an empty handler function.
import os
import boto3
from botocore.exceptions import ClientError
import img2pdf
from PIL import Image
def handle(event, context):
return {
"body": {
"message": "Hello world!"
},
"statusCode": 200
}
5. Before proceeding with the function’s logic, improve the Terraform code by adding the following code into your main.tf file:
resource "null_resource" "install_dependencies" {
provisioner "local-exec" {
command = <<-EOT
cd function
[ -d "./function/package" ] && rm -rf ./package
PYTHON_VERSION=3.11
docker run --rm -v $(pwd):/home/app/function --workdir /home/app/function rg.fr-par.scw.cloud/scwfunctionsruntimes-public/python-dep:$PYTHON_VERSION \
pip3 install --upgrade -r requirements.txt --no-cache-dir --target ./package
cd ..
EOT
}
triggers = {
hash = filesha256("./function/handler/large_messages.py")
}
}
data "archive_file" "function_zip" {
type = "zip"
source_dir = "./function"
output_path = "./function.zip"
depends_on = [null_resource.install_dependencies]
}
The null_resource is used to download and package the correct versions of the libraries that we use with the function. Learn more about this in the Scaleway documentation.
6. Create the function namespace.
resource "scaleway_function_namespace" "large_messages" {
name = "large-messages-function"
description = "Large messages namespace"
}
7. Add the resource to set up the function.
resource "scaleway_function" "large_messages" {
namespace_id = scaleway_function_namespace.large_messages.id
runtime = "python311"
handler = "handler/large_messages.handle"
privacy = "private"
zip_file = "function.zip"
zip_hash = data.archive_file.function_zip.output_sha256
deploy = true
memory_limit = "2048"
environment_variables = {
ENDPOINT_URL = scaleway_object_bucket.large_messages.api_endpoint
BUCKET_REGION = scaleway_object_bucket.large_messages.region
BUCKET_NAME = scaleway_object_bucket.large_messages.name
}
secret_environment_variables = {
ACCESS_KEY_ID = var.scw_access_key_id
SECRET_ACCESS_KEY = var.scw_secret_access_key
}
depends_on = [data.archive_file.function_zip]
}
The code sets up the function and connects it to the namespace. It tells the system to use Python version 3.11 and specifies which part of the Python file should run (the handler). It also adds important information, like environment variables and secrets, that our function will need to work correctly. Essential environment variables and secrets to use in our function logic are also added.
8. Create the function trigger to “wake up” the function when a NATS message come in.
resource "scaleway_function_trigger" "large_messages" {
function_id = scaleway_function.large_messages.id
name = "large-messages-trigger"
nats {
account_id = scaleway_mnq_nats_account.large_messages.id
subject = "large-messages"
}
}
It defines which account ID and subject to observe for getting messages.
9. Go back to large_messages.py and get the environment variables outside the hamdler function.
endpoint_url = os.getenv("ENDPOINT_URL")
bucket_region = os.getenv("BUCKET_REGION")
bucket_name = os.getenv("BUCKET_NAME")
access_key_id = os.getenv("ACCESS_KEY_ID")
secret_access_key = os.getenv("SECRET_ACCESS_KEY")
10. Get the input file name from the body, define the PDF file name from this and set up the s3 client to upload the file with Scaleway credentials.
input_file = event['body']
output_file = os.path.splitext(input_file)[0] + ".pdf"
s3 = boto3.client('s3', endpoint_url=endpoint_url,
region_name=bucket_region,
aws_access_key_id=access_key_id,
aws_secret_access_key=secret_access_key
11. Outside the handle function, create a new function convert_img_to_pdf.
def convert_img_to_pdf(img_path, pdf_path):
image = Image.open(img_path)
pdf_bytes = img2pdf.convert(image.filename)
file = open(pdf_path, "wb")
file.write(pdf_bytes)
image.close()
file.close()
print("Successfully made pdf file")
12. Download the image from the bucket using the s3 client.
s3.download_file(bucket_name, input_file, input_file)
print("Object " + input_file + " downloaded")
13. Convert the image with the dedicated function and reupload it in the bucket.
convert_img_to_pdf(input_file, output_file)
s3.upload_file(output_file, bucket_name, output_file)
print("Object " + input_file + " uploaded")
14. Put a try/except around the code to gracefully handle any errors coming from the S3 client.
try:
s3.download_file(bucket_name, input_file, input_file)
print("Object " + input_file + " downloaded")
convert_img_to_pdf(input_file, output_file)
s3.upload_file(output_file, bucket_name, output_file)
print("Object " + input_file + " uploaded")
except ClientError as e:
print(e)
return {
"body": {
"message": e.response['Error']['Message']
},
"statusCode": e.response['Error']['Code']
}
Test your work
All the infrastructure and the code of your function is ready, and you can now test your converter.
# Make sure your infrastructure is provisioned
terraform init
terraform apply
# Use your producer script
./upload_img.sh test.png #It can be any type of image
Conclusion, going further
In this introductory tutorial, we have demonstrated the usage of the NATS server for Messaging and Queuing, along with other services from the Scaleway ecosystem, to facilitate the transfer of large messages surpassing the typical size constraints. There are possibilities to expand upon this tutorial for various use cases, such as:
• Extending the conversion capabilities to handle different document types like docx.
• Sending of URLs directly to NATS and converting HTML content to PDF.
Docs APIScaleway consoleDedibox consoleScaleway LearningScaleway.comPricingBlogCarreer
© 2023-2024 – Scaleway | __label__pos | 0.999471 |
WebApi API
To use Samsung Product API,
<script type="text/javascript" src="$WEBAPIS/webapis/webapis.js"></script>
Should be loaded in index.html
This module defines the functionalities provided by the Tizen Samsung TV Product API.
Additionally, this specifies the location in the ECMAScript hierarchy in which the Tizen Samsung TV Product API is instantiated (window.webapis).
Since: 2.3
Product: TV, AV_BD
Summary of Interfaces and Methods
Interface Method
WebApiObject
WebApi
WebAPIException
WebAPIError
SuccessCallback
void onsuccess()
ErrorCallback
void onerror(WebAPIError error)
1. Interfaces
1.1. WebApiObject
This interface defines the webapis interface as a part of the window global object.
[NoInterfaceObject]interface WebApiObject {
readonly attribute WebApi webapis;
};
Window implements WebApiObject;
Attributes
• readonly WebApi webapis
Namespace for webapis.
1.2. WebApi
This interface defines the root of Tizen Samsung TV Product API.
[NoInterfaceObject]interface WebApi {};
1.3. WebAPIException
This interface defines Exception errors of APIs.
[NoInterfaceObject]interface WebAPIException {
readonly attribute unsigned long code;
readonly attribute DOMString name;
readonly attribute DOMString message;
const unsigned long INDEX_SIZE_ERR = 1;
const unsigned long DOMSTRING_SIZE_ERR = 2;
const unsigned long HIERARCHY_REQUEST_ERR = 3;
const unsigned long WRONG_DOCUMENT_ERR = 4;
const unsigned long INVALID_CHARACTER_ERR = 5;
const unsigned long NO_DATA_ALLOWED_ERR = 6;
const unsigned long NO_MODIFICATION_ALLOWED_ERR = 7;
const unsigned long NOT_FOUND_ERR = 8;
const unsigned long NOT_SUPPORTED_ERR = 9;
const unsigned long INUSE_ATTRIBUTE_ERR = 10;
const unsigned long INVALID_STATE_ERR = 11;
const unsigned long SYNTAX_ERR = 12;
const unsigned long INVALID_MODIFICATION_ERR = 13;
const unsigned long NAMESPACE_ERR = 14;
const unsigned long INVALID_ACCESS_ERR = 15;
const unsigned long VALIDATION_ERR = 16;
const unsigned long TYPE_MISMATCH_ERR = 17;
const unsigned long SECURITY_ERR = 18;
const unsigned long NETWORK_ERR = 19;
const unsigned long ABORT_ERR = 20;
const unsigned long URL_MISMATCH_ERR = 21;
const unsigned long QUOTA_EXCEEDED_ERR = 22;
const unsigned long TIMEOUT_ERR = 23;
const unsigned long INVALID_NODE_TYPE_ERR = 24;
const unsigned long DATA_CLONE_ERR = 25;
const unsigned long INVALID_VALUES_ERR = 26;
const unsigned long IO_ERR = 27;
const unsigned long SERVICE_NOT_AVAILABLE_ERR = 28;
const unsigned long UNKNOWN_ERR = 9999;
};
Constants
• INDEX_SIZE_ERR
The index is not in the allowed range.
• DOMSTRING_SIZE_ERR
The specified range of text is too large.
• HIERARCHY_REQUEST_ERR
The operation would yield an incorrect node tree.
• WRONG_DOCUMENT_ERR
The object is in the wrong document.
• INVALID_CHARACTER_ERR
The string contains invalid characters.
• NO_DATA_ALLOWED_ERR
Data is specified for a node that does not support data.
• NO_MODIFICATION_ALLOWED_ERR
The object cannot be modified.
• NOT_FOUND_ERR
The object cannot be found here.
• NOT_SUPPORTED_ERR
The operation is not supported.
• INUSE_ATTRIBUTE_ERR
The specified attribute is already in use elsewhere.
• INVALID_STATE_ERR
The object is in an invalid state.
• SYNTAX_ERR
The string did not match the expected pattern.
• INVALID_MODIFICATION_ERR
The object cannot be modified in this way.
• NAMESPACE_ERR
The operation is not allowed by Namespaces in XML.
• INVALID_ACCESS_ERR
The object does not support the operation or argument.
• VALIDATION_ERR
The operation would cause the node to fail validation.
• TYPE_MISMATCH_ERR
The type of the object does not match the expected type.
• SECURITY_ERR
The operation is insecure.
• NETWORK_ERR
A network error occurred.
• ABORT_ERR
The operation has been aborted.
• URL_MISMATCH_ERR
The given URL does not match another URL.
• QUOTA_EXCEEDED_ERR
The quota has been exceeded.
• TIMEOUT_ERR
The operation has timed out.
• INVALID_NODE_TYPE_ERR
The supplied node is incorrect or has an incorrect ancestor for this operation.
• DATA_CLONE_ERR
The object cannot be cloned.
• INVALID_VALUES_ERR
Input parameters contain an invalid value
• IO_ERR
IOs have error.
• SERVICE_NOT_AVAILABLE_ERR
Service is not available error.
• UNKNOW_ERR
This means an unknown error.
Attributes
• readonly unsigned short code
An error code value.
• readonly DOMString name
An error type name. The name attribute must return the value it had been initialized with.
• readonly DOMString message
An error message that describes the details of an encountered error.
1.4. WebAPIError
This interface will be used by the APIs in order to return them in the error callback of asynchronous methods.
[NoInterfaceObject]interface WebAPIError {
readonly attribute unsigned long code;
readonly attribute DOMString name;
readonly attribute DOMString message;
};
Attributes
• readonly unsigned short code
An error code value.
• readonly DOMString name
An error type name. The name attribute must return the value it had been initialized with.
• readonly DOMString message
An error message that describes the details of an encountered error.
1.5. SuccessCallback
This interface is used in methods that do not require any return value in the success callback.
[Callback = FunctionOnly, NoInterfaceObject]interface SuccessCallback {
void onsuccess();
};
Methods
onsuccess
Method invoked when the asynchronous call completes successfully.
void onsuccess();
Since: 2.3
Product: TV, AV_BD
Code example:
function onsuccess()
{
console.log("Success Callback is called.");
}
1.6. ErrorCallback
This interface is used in methods that require only an error as an input parameter in the error callback.
[Callback = FunctionOnly, NoInterfaceObject]interface ErrorCallback {
void onerror(WebAPIError error);
};
Methods
onerror
Method that is invoked when an error occurs.
void onerror(WebAPIError error);
Since: 2.3
Product: TV, AV_BD
Parameters:
• error: Generic error
Code example:
function onerror(error)
{
console.log(error.message);
}
2. Full WebIDL
module WebApi {
[NoInterfaceObject]interface WebApiObject {
readonly attribute WebApi webapis;
};
Window implements WebApiObject;
[NoInterfaceObject]interface WebApi {};
[NoInterfaceObject]interface WebAPIException {
readonly attribute unsigned long code;
readonly attribute DOMString name;
readonly attribute DOMString message;
const unsigned long INDEX_SIZE_ERR = 1;
const unsigned long DOMSTRING_SIZE_ERR = 2;
const unsigned long HIERARCHY_REQUEST_ERR = 3;
const unsigned long WRONG_DOCUMENT_ERR = 4;
const unsigned long INVALID_CHARACTER_ERR = 5;
const unsigned long NO_DATA_ALLOWED_ERR = 6;
const unsigned long NO_MODIFICATION_ALLOWED_ERR = 7;
const unsigned long NOT_FOUND_ERR = 8;
const unsigned long NOT_SUPPORTED_ERR = 9;
const unsigned long INUSE_ATTRIBUTE_ERR = 10;
const unsigned long INVALID_STATE_ERR = 11;
const unsigned long SYNTAX_ERR = 12;
const unsigned long INVALID_MODIFICATION_ERR = 13;
const unsigned long NAMESPACE_ERR = 14;
const unsigned long INVALID_ACCESS_ERR = 15;
const unsigned long VALIDATION_ERR = 16;
const unsigned long TYPE_MISMATCH_ERR = 17;
const unsigned long SECURITY_ERR = 18;
const unsigned long NETWORK_ERR = 19;
const unsigned long ABORT_ERR = 20;
const unsigned long URL_MISMATCH_ERR = 21;
const unsigned long QUOTA_EXCEEDED_ERR = 22;
const unsigned long TIMEOUT_ERR = 23;
const unsigned long INVALID_NODE_TYPE_ERR = 24;
const unsigned long DATA_CLONE_ERR = 25;
const unsigned long INVALID_VALUES_ERR = 26;
const unsigned long IO_ERR = 27;
const unsigned long SERVICE_NOT_AVAILABLE_ERR = 28;
const unsigned long UNKNOWN_ERR = 9999;
};
[NoInterfaceObject]interface WebAPIError {
readonly attribute unsigned long code;
readonly attribute DOMString name;
readonly attribute DOMString message;
};
[Callback = FunctionOnly, NoInterfaceObject]interface SuccessCallback {
void onsuccess();
};
[Callback = FunctionOnly, NoInterfaceObject]interface ErrorCallback {
void onerror(WebAPIError error);
};
}; | __label__pos | 0.986658 |
Fixes
Operation did not complete successfully because the file contains a virus [Fixed Completely]
Windows Virus and Threat protection or any other third-party antivirus software is essential to keep your system safe from Viruses that might attack your computer. Although these Softwares are very effective, sometimes they report false positives even if the file does not contain a virus. Quiet recently, users have reported an error that prevents them from opening a file or folder. It displays a message on the screen that states “Operation did not complete successfully because the file contains a virus”. If you have just encountered this error on your PC, don’t worry because we have compiled a guide that will help you fix it completely.
Operation did not complete successfully because the file contains a virus
The operation did not complete successfully because the file contains a virus Error Message
What prevents the operation from getting successful because of a virus?
After analyzing user reports, we concluded that there are several potential culprits that might end up triggering this error when you try to open a file or folder.
• Windows Virus and Threat protection: Windows Virus and threat protection or Windows Defender is responsible for filtering out data and information coming to your system. Mostly, the “Operation did not complete successfully because the file contains a virus” error arises if the Windows Defender is triggering a false alarm. Refer to the steps indexed in Solution 1.
• Antivirus blocking the file: Antivirus Softwares are essential to keep your system safe from viruses and threats. You might encounter this error message if your antivirus software has detected a virus in the file you are trying to open. However, this error can be fixed by whitelisting the file in your antivirus software. Follow the steps listed in Solution 2.
• Corrupted explorer.exe files: File explorer is a GUI for accessing the system files. Sometimes, explorer.exe can get corrupted and prevent you from launching the file explorer properly. These files can be fixed easily by running some commands in the command prompt. Please refer to Solution 3 to carry this task out.
• Internet Explorer’s Browser history: Internet Explorer keeps a track of every activity and updates its history every time you search something on the Internet. You might encounter the “Operation did not complete successfully because the file contains a virus” error on your computer if the Internet Explorer’s history is not cleared regularly. Therefore, to fix this error on your computer, follow the steps explained in Solution 4.
• Corrupted files on your disk: All of your disk partitions contain essential files and data that are needed by the applications and software installed on your computer to function properly. Sometimes, these files can get corrupted and trigger the “File Contains a virus” error on your computer. You can easily scan for these files and fix them by following the steps indexed in Solution 5.
• Faulty Software: Sometimes the installation files of certain software or application can get corrupted in the directory and it triggers this error when you try to launch that application. If this is the case, then it is a very hectic task to troubleshoot the issue and locate the exact root of the “Operation did not complete successfully because the file contains a virus” error. The most efficient approach to rectify this issue is to uninstall the application completely and then reinstall it.
Before we start:
Before you proceed towards troubleshooting the error, it is highly recommended to update your operating system. Follow the steps indexed below to carry this task out.
1. Press “Win+I” on your keyboard to open “Settings” and navigate to “Update and Security”.
Update and Security
Update and Security
2. From the left pane select “Windows Security” and click on “Virus and threat protection” from the right side of the window.
Virus and threat protection
Virus and threat protection
3. Now click on “Check for updates” under the “Virus and threat protection updates” section.
Virus and threat protection updates
Virus and threat protection updates
4. Click on the “Check for updates” button and wait while the computer installs an updated version of this program.
Check for updates to fix Operation did not complete successfully because the file contains a virus error
Check for updates
5. After this process is completed, restart your computer and check if the issue persists.
Fixing the “Operation did not complete successfully because the file contains a virus” Error on Windows 10:
Solution 1: Disable Windows virus and threat protection
1. Press “Win+I” on your keyboard to open “Settings” and navigate to “Update and Security”.
Update and Security
Update and Security
2. From the left pane select “Windows Security” and click on “Virus and threat protection” from the right side of the window.
Virus and threat protection
Virus and threat protection
3. Now click on “Manage Settings” under the “Virus and threat protection settings” section.
Manage Settings
Manage Settings
4. Disable the toggle button that is associated with “Real-Time Protection”, “Cloud delivery protection”, and “Automatic sample submission”.
Disable Windows virus and threat protection to fix Operation did not complete successfully because the file contains a virus error
Disable Windows virus and threat protection
5. Now press the “Win + R” keys on the keyboard to open the Run box and search for “gpedit.msc”.
gpedit.msc
gpedit.msc
6. Navigate to the following location from the left pane:
Computer Configuration > Administrative Templates > Windows Components > Windows Defender
7. Locate and select “Turn off windows defender” from the right pane.
8. Now click on the “Enable” option and apply the changes.
Clicking on the "Enabled" option
Clicking on the “Enabled” option
9. Now restart your computer and check if the “Operation did not complete successfully because the file contains a virus” error persists.
Solution 2: Whitelist problematic folder in your anti-virus programs
For Windows Virus and threat protection:
1. Press “Win+I” on your keyboard to open “Settings” and navigate to “Update and Security”.
Update and Security
Update and Security
2. From the left pane select “Windows Security” and click on “Virus and threat protection” from the right side of the window.
Virus and threat protection
Virus and threat protection
3. Now click on “Manage Settings” under the “Virus and threat protection settings” section.
Manage Settings
Manage Settings
4. Scroll down and click on “Add or remove exclusion” under the “Exclusion” section.
Add or remove exclusion
Add or remove exclusion
5. Now click on “Add an Exclusion” and add your file or folder you are having trouble with.
Add an Exclusion to fix Operation did not complete successfully because the file contains a virus error
Add an Exclusion
6. Now check and see if the error is terminated.
Avast:
1. From the home screen of your anti-virus software, navigate to the “Settings”.
Settings
Settings
2. Now navigate to the “General” tab and click on the “Exclusion” section.
Exclusion
Exclusion
3. Now add the path to the problematic file to add it as an exception to the anti-virus.
Add the path to the problematic file to fix Operation did not complete successfully because the file contains a virus error
Add the path to the problematic file
Solution 3: Fix Windows Explorer using the command prompt
1. Press the “Win + R” keys on the keyboard to open the Run box. Type “cmd” and hit the “Shift + Ctrl + enter” keys on the keyboard simultaneously to open it as administrator.
Open Command Prompt as admin
Open Command Prompt as admin
2. Type the following commands and then hit enter to execute them.
sfc /SCANFILE=C:\windows\explorer.exe
sfc /SCANFILE=C:\Windows\SysWow64\explorer.exe
Performing SFC Scan to fix the Operation did not complete successfully because the file contains a virus error
Performing SFC Scan
3. After the execution of these commands, a message will be displayed on the screen stating “Windows Resource Protection found corrupt files and successfully repaired them”.
Solution 4: Clear browsing history of Internet Explorer
From Control Panel:
1. Press the “Win + R” keys on the keyboard to open the Run box and search for “Control Panel”.
Typing in Control Panel
Typing in Control Panel
2. From the top-right corner, choose “View by Large icon” and then select “Internet Options”
Internet Options
Internet Options
3. In the “General” tab, check the box parallel to “Delete browsing history on exit”.
Delete browsing history on exit to fix the Operation did not complete successfully because the file contains a virus error
Delete browsing history on exit
4. Now apply the changes and restart your PC.
From the browser:
1. Launch Internet Explorer on your computer and click on the “Setting cog” at the top-right of the screen.
2. Hover your cursor on “Safety” and select “Delete browsing history”.
Delete Browsing History
Delete Browsing History
3. Now check all the boxes displayed in the Window and click on the “Delete” button.
Clear browsing history of Internet Explorer
Clear browsing history of Internet Explorer
Solution 5: Use Disk Cleanup to clean your disks
1. Press “Win+R” on your keyboard and search for “cleanmgr”.
cleanmgr
cleanmgr
2. Now select the disk partition from the drop-down list and click on “OK”.
Select the disk partition
Select the disk partition
3. Check the box parallel to “Temporary Internet files” and select “OK”.
Temporary Internet files
Temporary Internet files
4. Now click on “Delete Files” and check if the issue persists.
Delete Files to fix the Operation did not complete successfully because the file contains a virus error
Delete Files
Solution 6: Perform a system restore
1. Press the “Win + R” keys on the keyboard to open the Run box and search for “rstrui”.
rstrui
rstrui
2. Select a restore point that was created before you came across the”Operation did not complete successfully because the file contains a virus” error.
Perform a system restore to fix Operation did not complete successfully because the file contains a virus error
Perform a system restore
3. Click “Next” and then choose “Finish”.
4. Check if the error is terminated after the system gets restored.
Solution 7: Perform a clean boot
1. Press the “Win + R” keys on the keyboard to open the Run box and search for “msconfig”.
Typing in "Msconfig"
Typing in “Msconfig”
2. Navigate to the “Services” tab and check the box parallel to “Hide all Microsoft services”.
Hide all Microsoft services
Hide all Microsoft services
3. Now click on the “Disable All” option and apply the changes.
4. Navigate to the “Startup” tab and click on “Open Task Manager”.
Open Task Manager
Open Task Manager
5. Now right-click on each service one by one and select “Disable”.
Disable to fix Operation did not complete successfully because the file contains a virus error
Disable
6. Now close the task manager and restart your PC to check if the error persists.
Solution 8: Reinstall the faulty software
1. Press the “Win + R” keys on the keyboard to open the Run box and search for “Control Panel”.
Typing in Control Panel
Typing in Control Panel
2. Now click on “Uninstall a program”.
Uninstall a program
Uninstall a program
3. Locate the application you are having trouble with, right-click on it and select “Uninstall”.
Uninstall to fix the Operation did not complete successfully because the file contains a virus error
Uninstall
4. After the problematic application is completely uninstalled, launch your browser and download the latest version of that application.
5. Double-click on the downloaded executable and follow the on-screen instructions to install the program.
6. After it is installed successfully, check and see if the error is rectified.
Solution 9: Reinstall third-party antivirus
The “Operation did not complete successfully because the file contains a virus” error mostly occurs on your computer if there is an issue with the third-party antivirus software installed on it. If the antivirus software is not functioning properly then the most efficient approach to fix it is by reinstalling the software. If, after reinstalling the software, the error persists, then we recommend you to disable the antivirus software and try to open the problematic file again. If this resolves your error then keep the things that way and do not enable the antivirus again but if you still encounter the error, then it is highly recommended to switch to a different antivirus. Many users have reported that they rectified this error from their computer completely by switching to BullGuard antivirus software.
Solution 10: Perform a full system scan
If you still see the “Operation did not complete successfully because the file contains a virus” error message on the screen, we recommend you perform a full system scan to locate and fix all the corrupted files in your system. An efficient approach to carry this task out is to use a third-party software called Restoro. It is an advanced system repair tool that will remove malware, replace damaged windows files, and restore your system performance to its maximum.
Solution 11: Reset your Windows
1. Press “Win+I” on your keyboard to open “Settings” and navigate to “Update and Security”.
Update and Security
Update and Security
2. From the left pane, navigate to “Recovery” and click on “Get started” under the “Reset this PC” section.
Reset this PC
Reset this PC
3. Now select “Keep my files” and follow the onscreen instructions to reset your PC.
Keep my files to fix the Operation did not complete successfully because the file contains a virus error
Keep my files
4. When the process is completed, open the problematic file to verify if the “Operation did not complete successfully because the file contains a virus” error is eliminated.
By now you should’ve managed to fix the error but if you are still facing it, make sure to contact us.
Back to top button
DMCA.com Protection Status | __label__pos | 0.829776 |
What Is A 70/30 Ratio?
What is 70% as a ratio?
Convert fraction (ratio) 70 / 100 Answer: 70%.
What is the formula for a ratio?
The most common way to write a ratio is as a fraction, 3/6. We could also write it using the word “to,” as “3 to 6.” Finally, we could write this ratio using a colon between the two numbers, 3:6. Be sure you understand that these are all ways to write the same number.
What is the ratio of 30 to 70?
Latest decimal numbers, fractions, rations or proportions converted to percentages70 / 30 = 233.333333333333%Nov 26 19:30 UTC (GMT)81 / 709 = 11.424541607898%Nov 26 19:30 UTC (GMT)35 / 65 = 53.846153846154%Nov 26 19:30 UTC (GMT)9 / 8 = 112.5%Nov 26 19:30 UTC (GMT)11 / 17 = 64.705882352941%Nov 26 19:30 UTC (GMT)9 more rows
What number is 70% of 100?
142.85714285714370 percent (calculated percentage %) of what number equals 100? Answer: 142.857142857143.
What is a 70/30 ratio?
70/10 = 7 and 30/10 = 3. Thus, 70:30 ratio simplified is 7:3.
What is the ratio of 2 to 4?
1:2Multiplying or dividing each term by the same nonzero number will give an equal ratio. For example, the ratio 2:4 is equal to the ratio 1:2.
What is the ratio of 5 to 9?
Simplify Ratio 5:9. Here we will simplify the ratio 5:9 for you and show you how we did it. To simplify the ratio 5:9, we find the greatest common divisor of 5 and 9, and then we divide 5 and 9 by the greatest common divisor.
What is the ratio of 15 to 100?
15%Convert fraction (ratio) 15 / 100 Answer: 15%
How do I solve a ratio problem?
To solve this question, you must first add together the two halves of the ratio i.e. 4 + 2 = 6. Then you need to divide the total amount using that number i.e. 600/6 = 100. To work out how much each person gets, you then multiply their share by 100.
What is the ratio of 3 to 5?
3 : 5 = ? : 40. (3 out of 5 is how many out of 40?)
What is the ratio of 3 to 4?
The simplified or reduced ratio “3 to 4” tells us only that, for every three men, there are four women. The simplified ratio also tells us that, in any representative set of seven people (3 + 4 = 7) from this group, three will be men. In other words, the men comprise 73 of the people in the group.
What is a 70% out of 100?
What is 70 percent (calculated percentage %) of number 100? Answer: 70.
How do you calculate a 70/30 ratio?
Follow the same procedure for other weighting ratios (for a 70 — 30 split, multiply the first number by 7, the second by 3, and divide their sum by 10; and so on).
What is the ratio of 40 to 70?
57.142857142857%Convert fraction (ratio) 40 / 70 Answer: 57.142857142857%
What is 14 out of 70 as a percentage?
20%How much is – 14 out of 70 written as a percent value? Convert fraction (ratio) – 14 / 70 Answer: -20% | __label__pos | 1 |
Presentation is loading. Please wait.
Presentation is loading. Please wait.
COMP 321 Week 13. Overview Filters Scaling and Remote Models MVC and Struts.
Similar presentations
Presentation on theme: "COMP 321 Week 13. Overview Filters Scaling and Remote Models MVC and Struts."— Presentation transcript:
1 COMP 321 Week 13
2 Overview Filters Scaling and Remote Models MVC and Struts
3 Problem We have a working web application with many Servlets. Now we decide we need to keep track of how many times each users accesses each Servlet How can we do this without modifying each Servlet?
4 Filters Can intercept requests before they are passed to the servlet, and intercept responses before they are returned to the client Can be chained together
5 Filters Request filters can: Perform security checks Perform security checks Reformat request headers or bodies Reformat request headers or bodies Audit or log requests Audit or log requests Response filters can: Compress the response stream Compress the response stream Append to or alter the response stream Append to or alter the response stream Create an entirely different response Create an entirely different response Difference between a request and response filter is only the programmers intention – there is no actual difference in implementation!
6 Logging Requests public class BeerRequestFilter implements Filter { private FilterConfig fc; public void init(FilterConfig config) throws ServletException { this.fc = config; } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpReq = (HttpServletRequest) req; String name = httpReq.getRemoteUser(); if (name != null) { fc.getServletContext().log("User " + name + " is updating"); } chain.doFilter(req, resp); }
7 Declaring and Ordering Filters BeerRequest com.example.web.BeerRequestFilter LogFileName UserLog.txt BeerRequest *.do BeerRequest AdviceServlet
8 Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /Recipes/HopsReport.do
9 Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /Recipes/HopsReport.doFilters: 1, 5
10 Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /Recipes/HopsList.do
11 Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /Recipes/HopsList.doFilters: 1, 5, 2
12 Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /Recipes/Modify/ModRecipes.do
13 Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /Recipes/Modify/ModRecipes.doFilters: 1, 5, 4
14 Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /HopsList.do
15 Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /HopsList.doFilters: 5
16 Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /Recipes/Add/AddRecipes.do
17 Sharpen Your Pencil Filter1 /Recipes/* Filter2 /Recipes/HopsList.do Filter3 /Recipes/Add/* Filter4 /Recipes/Modify/ModRecipes.do Filter5 /* Request: /Recipes/Add/AddRecipes.doFilters: 1, 3, 5
18 Response Filters What if we want to compress the response? How can we do this? Will this work? public void doFilter(…) { // request handling chain.doFilter(request, response); // do compression here }
19 Response Filters By the time the filter gets the response back, the servlet has already written to the output stream in the response, and the data has been sent back to the browser We need to intercept this data somehow
20 Response Filters public class CompressionResponseWrapper extends HttpServletResponseWrapper { public ServletOutputStream getOutputStream() throws IOException { return new GZIPOutputStream(getResponse().getOutputStream()); } public class MyCompressionFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { CompressionResponseWrapper wrappedResp = new CompressionResponseWrapper(response); chain.doFilter(request, wrappedResp); //Some compression logic here? }
21 Response Filters public class CompressionResponseWrapper extends HttpServletResponseWrapper { public ServletOutputStream getOutputStream() throws IOException { return new GZIPOutputStream(getResponse().getOutputStream()); } public class MyCompressionFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { CompressionResponseWrapper wrappedResp = new CompressionResponseWrapper(response); chain.doFilter(request, wrappedResp); //Some compression logic here? } Problems: getOutputStream() returns a new stream each time it's called GZIPOutputStream is not a ServletOutputStream GZIPOutputStream.finish() must be called
22 Response Filters public class MyCompressionFilter implements Filter { private FilterConfig cfg; private ServletContext public void init(FilterConfig cfg) throws ServletException { this.cfg = cfg; ctx = cfg.getServletContext(); ctx.log(cfg.getFilterName() + " initialized."); public void destroy() { cfg = null; ctx = null; }
23 Response Filters public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest)req; HttpServletResponse response = (HttpServletResponse)resp; String validEncodings = request.getHeader("Accept-Encoding"); if(validEncodings.indexOf("gzip") > -1) { CompressionResponseWrapper wrappedResp = new CompressionResponseWrapper(response); wrappedResp.setHeader("Context-Encoding", "gzip"); chain.doFilter(request, wrappedResp); wrappedResp.finishGZIP(); ctx.log(cfg.getFilterName() + ": finished the request."); } else { ctx.log(cfg.getFilterName() + ": no encoding performed."); chain.doFilter(request, response); }
24 Response Filters public class CompressionResponseWrapper extends HttpServletResponseWrapper { private GZIPServletOutputStream gzos = null; private PrintWriter pw = null; private Object streamUsed = null; public CompressionResponseWrapper(HttpServletResponse response) { super(response); } public void finishGZIP() throws IOException { gzos.finish(); }
25 Response public ServletOutputStream getOutputStream() throws IOException { if(streamUsed != null && streamUsed != gzos) throw new IllegalStateException(); if(gzos == null) { gzos = new GZIPServletOutputStream(getResponse().getOutputStream()); streamUsed = gzos; } return gzos; }
26 Response public PrintWriter getWriter() throws IOException { if(streamUsed != null && streamUsed != pw) throw new IllegalStateException(); if(pw == null) { gzos = new GZIPServletOutputStream(getResponse().getOutputStream()); OutputStreamWriter osw = new OutputStreamWriter(gzos, getResponse().getCharacterEncoding()); pw = new PrintWriter(osw); streamUsed = pw; } return pw; }
27 Response Filters public class GZIPServletOutputStream extends ServletOutputStream { GZIPOutputStream os; public GZIPServletOutputStream(ServletOutputStream sos) throws IOException { this.os = new GZIPOutputStream(sos); } public void finish() throws IOException { os.finish(); } public void write(int param) throws IOException { os.write(param); }
28 Horizontal Scaling Enterprise web applications can get hundreds of thousands of hits per day To handle this volume, work must be distributed across many machines Hardware is normally configured in tiers, and increased load can be handled by adding machines to a tier
29 Horizontal Scaling
30 Two Classes of Requirements Functional: Application operates correctly Application operates correctlyNon-Functional: Performance Performance Modularity Modularity Flexibility Flexibility Maintainability Maintainability Extensibility Extensibility How do we make sure we can handle these?
31 To Meet Non-functional Requirements Code to interfaces Separation of Concerns Cohesion Hiding Complexity Loose Coupling Increase Declarative Control
32 Improving the Beer App Current Implementation: 1.Web request received, Controller calls ManageCustomer service, and gets a Customer bean back 2.Controller adds Customer bean to request object 3.Controller forwards to the View JSP 4.JSP uses EL to get properties and generate page
33 Local Model
34 Question How can we put the components on different servers and have them still talk to each other?
35 Solution JNDI – supplies centralized network service for finding things RMI – allows method calls to objects on different machines
36 JNDI Java Naming and Directory Interface Maintains a registry of objects Allows object lookup via locator string Allows objects to be relocated transparently - clients dont need to know
37 RMI Remote method invocation Allows methods on an object to be called from a client on a different machine Moving parameters and return values across the network requires only that they be Serializable
38 RMI (contd) – Server Side 1. Create a remote interface 2. Create implementation 3. Generate stub and skeleton 4. Register objects
39 RMI (contd) – Client Side 1. Look up object 2. Call methods normally
40 Design Issues We would like to use the same controller whether the model is local or remote –How do we handle RMI lookups? –How do we handle remote exceptions?
41 Solution We need a go-between to handle these things - the Business Delegate
42 Business Delegate Looks like a model object - implements same interface Connects to the real model object via RMI Delegates all calls to the real model object (possibly across the network)
43 Service Locator Helps avoid duplicating code in Business Delegates Responsible for locating objects via JNDI, and returning stubs to Business Delegates
44 Local Model (Take #2)
45 Remote Model 1. Register services with JNDI 2. Use Business Delegate and Service Locator to get ManageCustomer stub from JNDI 3. Use Business Delegate and stub to get Customer bean (another stub), and return to Controller 4. Add Customer stub to request 5. Forward to View JSP 6. View JSP uses EL to get properties from Customer bean, unaware that it isnt the actual bean
46 Remote Model
47 Remote Model - Downsides Fine-grained calls to get properties cause a large performance hit JSP shouldnt have to handle remote exceptions How can we solve these problems?
48 Solution – Transfer Objects! Remember Transfer Object? Serializable beans that can be returned across remote interfaces Serializable beans that can be returned across remote interfaces Prevent simple get/set calls from having to traverse network boundaries Prevent simple get/set calls from having to traverse network boundaries See Week 5 slides See Week 5 slides
49 Return to MVC Where we left off… Each view was a JSP Each view was a JSP Data was held in model classes Data was held in model classes Each URL had its own controller, and there was a lot of duplicated code between them Each URL had its own controller, and there was a lot of duplicated code between them
50 Controller protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Dealing with request... String c = request.getParameter("startDate"); // Do data conversion on date parameter // Validate that date is in range // If any errors happen, forward to hard-coded retry JSP // Dealing with model... // Invoke hard-coded model components // add model results to request object // Dealing with view... // dispatch to hard-coded view JSP }
51 Controller protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Dealing with request... String c = request.getParameter("startDate"); // Do data conversion on date parameter // Validate that date is in range // If any errors happen, forward to hard-coded retry JSP // Dealing with model... // Invoke hard-coded model components // add model results to request object // Dealing with view... // dispatch to hard-coded view JSP } The controller is tightly coupled to the model and views, and we also have issues with duplicate code. How can we split this up?
52 Controller 1. Handle request – give this task to a separate validation component 2. Invoke model – declaratively list models that should be used 3. Dispatch to the view – declaratively define views to be used based on controller results
53 Introducing Struts 1. Controller receives request, looks up Form Bean, sets attributes, and calls validate() 2. Controller looks up Action Object, calls execute() 3. Using result of action, Controller forwards request to correct view
54 Struts (contd)
55 Moving to Struts public class BeerSelectForm extends ActionForm { private String color; public void setColor(String color) { this.color = color; } public String getColor() { return color; } private static final String VALID_COLORS = "amber,dark,light,brown"; public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) { ActionErrors errors = new ActionErrors(); if(VALID_COLORS.indexOf(color) == -1) { errors.add("color", new ActionMessage("error.colorField.notValid"); } return errors; }
56 Moving to Struts public class BeerSelectAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { BeerSelectForm myForm = (BeerSelectForm)form; //Process the business logic BeerExpert be = new BeerExpert(); List result = be.getBrands(myForm.getColor()); //Forward to the results view request.setAttribute("styles", result); return mapping.findForward("show_results"); }
57 Moving to Struts ...
58 Progress Check Due this week –Lab 12-1 Wrapper Design Problem Due next week –Lab 10-1 JSP User Interfaces –Lab 13-1 Web Frameworks
Download ppt "COMP 321 Week 13. Overview Filters Scaling and Remote Models MVC and Struts."
Similar presentations
Ads by Google | __label__pos | 0.974967 |
Märt Matsoo - my site, your time
Märt Matsoo laughing
Current: Tallinn
Team: Chromatic
Position: Developer
I.T. Work Experience 17 years and 25 days | Education University of Toronto
My musings & posts:
Pesky space screwed up string comparison in javascript
Located in:
I implemented a small script to recognise IE 6 or 7 browsers and tell them to upgrade or switch away from IE totally. It's a jQuery fade-in box at the top of the page. After offering that the user should either upgrade or switch to another browser I provide a "hide this warning for the rest of your visit" link. Clicking the link sets a cookie value that is then used to hide the IE warning for the rest of the session. (ie. hide_ie_warning = 1)
When does content type count get ridiculous?
Located in:
This is just a small, personal site built for experimentation and fun, but I already have 8 content types to choose from when I want to add a new article. Without fact checking, I think Drupal has about 3 content types (Page, Story and Blog?) when freshly installed. However, the templating system in Drupal is so powerful and, dare I say it, intuitively structured that - once you get it - it's easy to have an explosion of content types and corresponding template files to suit your needs. But when does it get out of hand?
Inline list items were breaking where they shouldn't
Located in:
One of my Drupal modules (combined with a node template) looks for (intra-article) anchor links at the beginning of the article code and then dynamically builds a menu with these links at the top of the article. (This was a somewhat messy but effective way of bringing old content with anchor links into a new environment without having to re-write the old article code.) So what? Well, it turns out a lack of white space / line breaks in my code was messing with my layout. I'll try to show you what I mean.
Banner pollution caused by zombies?
Located in:
Browsers come with pop-up blockers and banner ad blockers and all sorts of add-ons to make sites less blinky and less annoying. I can't remember anyone ever saying they like or look at banner ads. (okay, I mainly read web development stuff, but still...) Usability tests show that experienced users have developed banner blindness and don't even look at things with typical banner ad dimensions.
Changing "Search this site" text in Drupal
Located in:
I like Drupal a lot and you could say I am committed to it, but just like in any relationship, there are little things that make you scratch your head. Changing default site text ("Search this site", "Read more" etc.) is one of those things. It should be simple. Perusing Drupal forums and seeing some of the solutions people have resorted to (ie. hacking core, rolling a custom module just to implement hook_form_alter) makes you wonder if this CMS isn't just a bit too complex.
How about that! I'm a Drupal association member.
Attention IE user!
It turns out you are using an outdated browser and my site might look a bit weird for you. (images are off colour, text gets cut off, layout is wacky) This is because your browser does not implement web standards. Please consider an upgrade.
Alternatively, you can try other browsers like Google Chrome, Mozilla Firefox, Opera or Apple's Safari. Every web developer on the planet will thank you! (and that's not really an exaggeration)
Hide this notice for the rest of your visit | __label__pos | 0.534259 |
appfordown applications
Appfordown Applications Unveiled: Features, Benefits, and User Experiences
In the modern digital world, mobile and desktop applications have become an integral part of our everyday lives. Among these, “Appfordown” apps have stood out for their distinctive features and offerings. This in-depth guide takes a closer look at Appfordown applications, examining their characteristics, advantages, and the influence they have on users.
What are Appfordown Applications?
Appfordown applications represent a class of software tailored to assist users in managing a variety of tasks and activities. These apps are known for their intuitive interfaces, extensive features, and capacity to boost both productivity and entertainment. Spanning multiple areas such as education, business, entertainment, health, and personal finance, they serve as versatile tools for a wide range of users.
Essential Elements of Appfordown Programs
A key highlight of Appfordown applications is their easy-to-use interface. These apps are crafted to be straightforward, allowing even those with limited technical skills to navigate and use them with ease. Moreover, Appfordown applications come packed with a variety of features that meet diverse needs and preferences. Whether it’s managing tasks, accessing educational materials, enjoying entertainment, or tracking health, these apps offer well-rounded solutions for everyday tasks.
Well-liked Applications for Downtime
Many Appfordown applications have become popular because of their innovative features and dependable performance. Examples include productivity apps for note-taking and task management, educational apps that deliver interactive learning experiences, and entertainment apps offering a wide range of media content. These applications have become indispensable for countless users, playing a significant role in their everyday lives.
Appfordown Applications’ Advantages
Appfordown applications offer a wide range of benefits. First, they significantly boost productivity by offering effective tools for managing tasks, schedules, and projects, helping users stay organized and streamline their work processes. Second, these applications provide educational advantages by granting access to vast knowledge and learning resources, making them invaluable for students and lifelong learners alike. Lastly, Appfordown apps support personal well-being by incorporating health and fitness tracking features, motivating users to lead healthier lives.
How to Install and Download Appfordown Apps
Downloading and installing Appfordown applications is simple and easy. Users can either visit the official Appfordown website or navigate to their device’s app store, search for the specific app they want, and follow the provided instructions to download and install it. The process is typically quick and smooth, enabling users to begin using the app in just a few minutes.
Interface Design and User Experience
Appfordown applications are designed with great attention to user experience (UX) and interface design, creating a smooth and enjoyable experience for users. The apps feature intuitive navigation, attractive layouts, and responsive designs that adjust seamlessly to various screen sizes and devices. This emphasis on UX and design makes it easy for users to interact with the apps, greatly improving their overall experience.
Measures for Security and Privacy
Ensuring security and privacy is a top priority for Appfordown applications. They incorporate strong security features, such as encryption and secure login processes, to protect users’ data. Additionally, regular updates are deployed to fix any vulnerabilities, so users can feel confident that their personal information remains secure while using the app.
Customer Service and Involvement in the Community
Appfordown applications come with extensive customer support options. Users can get assistance through email, live chat, and community forums. The company also nurtures an active user community where individuals can exchange tips, ask questions, and discuss their experiences with the apps. This vibrant community interaction enhances the user experience, offering both support and a sense of connection.
Appfordown: Business Applications
Businesses stand to gain a lot from using Appfordown applications. These tools provide features for project management, team collaboration, and customer relationship management (CRM), among others. By using these applications, companies can simplify their workflows, boost communication, and increase overall productivity. Appfordown also supports remote work, allowing teams to stay engaged and efficient no matter where they are.
Applications for Education on Appfordown
In education, these applications are invaluable resources for both students and teachers. They offer interactive learning experiences, access to educational materials, and tools for managing coursework and assignments. This fosters active learning and helps students build crucial skills. For teachers, these apps provide essential tools for lesson planning, grading, and staying in touch with students and parents.
Appfordown: Entertainment Applications
In the entertainment sphere, Appfordown applications truly excel. They offer a diverse array of options, from streaming movies and TV shows to listening to music and playing games. With top-notch content and smooth streaming experiences, these apps make it easy for users to relax and enjoy their favorite entertainment.
Appfordown: Health and Fitness Applications
For health and fitness enthusiasts, Appfordown applications are a great asset. They provide features for tracking workouts, monitoring diets, and analyzing health metrics. With these tools, users can stay motivated, keep an eye on their progress, and make informed choices about their health and fitness routines.
Prospective Advancements and Novelties
The future of Appfordown applications is bright, with ongoing advancements and innovations on the way. Developers are dedicated to improving current features and adding new ones to keep up with users’ changing needs. Emerging technologies like artificial intelligence (AI) and machine learning (ML) are set to significantly influence the future of these apps, providing more personalized and intelligent experiences.
Obstacles and Things to Think About
Despite the many advantages of Appfordown applications, there are challenges to consider. One key issue is ensuring that the apps work well across different devices and operating systems. Developers need to put in extra effort to make sure the applications run smoothly on various platforms. Additionally, responding to user feedback and making ongoing improvements is essential for keeping users satisfied and loyal.
Conclusion
Appfordown applications have become essential tools for millions of users around the globe. Thanks to their intuitive interfaces, wide range of features, and numerous advantages, these apps boost productivity, support education, offer entertainment, and enhance health, among other benefits. As technology evolves, the future of these applications looks promising, with potential for even more innovative and valuable solutions. Whether for personal or professional use, Appfordown applications are set to continue playing a vital role in our digital lives.
FAQs
1. What are Appfordown applications?
Appfordown applications are versatile software tools designed to help users manage various tasks and activities. They offer features across multiple domains, including education, business, entertainment, health, and personal finance, with an emphasis on user-friendly interfaces and extensive functionalities.
2. What are the key features of Appfordown applications?
Appfordown applications are known for their intuitive interfaces, diverse features, and ability to enhance productivity and entertainment. They include tools for task management, educational resources, entertainment options, and health tracking, catering to a wide range of user needs.
3. How can businesses benefit from using Appfordown applications?
Businesses can leverage Appfordown applications for project management, team collaboration, and customer relationship management (CRM). These tools help streamline workflows, improve communication, and increase overall productivity. The applications also support remote work, allowing teams to stay connected and efficient from any location.
4. How do Appfordown applications support education?
In education, Appfordown applications provide interactive learning experiences, access to educational materials, and tools for managing coursework and assignments. They facilitate active learning, help students build essential skills, and offer educators tools for lesson planning, grading, and communication with students and parents.
5. What are some popular Appfordown applications for entertainment?
Appfordown applications excel in entertainment by offering a variety of options such as streaming movies and TV shows, listening to music, and playing games. These apps provide high-quality content and smooth streaming experiences for users to enjoy their favorite entertainment.
6. How do Appfordown applications aid in health and fitness?
Appfordown applications for health and fitness include features for tracking workouts, monitoring diets, and analyzing health metrics. These tools help users stay motivated, monitor their progress, and make informed decisions about their health and fitness routines.
7. How can I install and download Appfordown applications?
To install and download Appfordown applications, visit the official Appfordown website or your device’s app store. Search for the app you want, and follow the instructions to download and install it. The process is generally quick and straightforward.
8. What measures do Appfordown applications take to ensure security and privacy?
Appfordown applications prioritize security and privacy by incorporating encryption, secure login processes, and regular updates to address vulnerabilities. These measures help protect users’ data and ensure that personal information remains secure.
9. What kind of customer support does Appfordown offer?
Appfordown provides extensive customer support through email, live chat, and community forums. They also foster an active user community where individuals can exchange tips, ask questions, and discuss their experiences with the applications.
10. What are the future prospects for Appfordown applications?
The future of Appfordown applications looks promising with ongoing advancements and innovations. Developers are working on enhancing current features and introducing new ones, with emerging technologies like artificial intelligence (AI) and machine learning (ML) expected to offer more personalized and intelligent experiences.
11. What challenges do Appfordown applications face?
Appfordown applications face challenges such as ensuring compatibility across various devices and operating systems. Developers must also continuously respond to user feedback and make improvements to maintain user satisfaction and loyalty.
Stay informed about celebrity events and happenings on tamasha.blog
Similar Posts
Leave a Reply
Your email address will not be published. Required fields are marked * | __label__pos | 0.987823 |
WordPress как на ладони
wordpress jino
wp_get_shortlink() WP 3.0.0
Возвращает короткую ссылку на статью (пост).
Эта функция существует, чтобы создавать короткую, неизменную ссылку в шаблонах и плагинах, использовать которую можно будет вне зависимости от установленного типа ЧПУ.
Этот тег шаблона предназначен для получения короткой ссылки на пост/блог, когда на блоге включено ЧПУ (Человеко-понятные УРЛ). Такую короткую ссылку удобно использовать для размещения заметок в социальных сетях (twitter).
Такие, короткие, внешние ссылки никак отрицательно не сказывается на поисковой оптимизации (SEO), потому что при переходе по такой ссылке, поискового робота перекидывает на нормальный УРЛ с использованием 301 редиректа (указание что страница перемещена), в результате чего весь вес передается оригинальной странице.
Используется в: the_shortlink().
Хуки из функции:
Возвращает
Строку. Короткую ссылку или пустую строку, если короткой ссылки не существует на запрашиваемый ресурс, или если ссылка не доступна.
Использование
echo wp_get_shortlink($id, $context, $allow_slugs);
$id(число)
ID поста или блога. По умолчанию 0, значит что используется текущий блог или пост.
По умолчанию: 0 (текущий пост)
$context(строка)
Пояснение какой ID указан в параметре $id:
• post - ID поста;
• blog - ID блога;
• media - медиа-файла;
• query- будет выведена короткая ссылка текущего запроса (параметры $id и $context будут получены из текущего запроса).Если указано post (по умолчанию), то тип поста будет установлен автоматически.
По умолчанию: 'post'
$allow_slugs(логический)
Допускать ли использование слагов (альтернативных названий) в ссылках. Этот параметр предназначен для хуков и плагинов.
По умолчанию: true
Примеры
#1. Базовый пример
Выведем короткую ссылку на текущую статью:
echo 'Короткая ссылка: '. wp_get_shortlink();
// получим
// Короткая ссылка: http://example.com/?p=1234
#2 Удалим короткую ссылку из заголовков
Этот пример показывает, как удалить короткую ссылку из HEAD части документа и из заголовков ответа сервера, где также добавляется короткая ссылка:
remove_action('wp_head', 'wp_shortlink_wp_head');
remove_action('template_redirect', 'wp_shortlink_header', 11);
Код wp get shortlink: wp-includes/link-template.php VER 4.9.4
<?php
function wp_get_shortlink( $id = 0, $context = 'post', $allow_slugs = true ) {
/**
* Filters whether to preempt generating a shortlink for the given post.
*
* Passing a truthy value to the filter will effectively short-circuit the
* shortlink-generation process, returning that value instead.
*
* @since 3.0.0
*
* @param bool|string $return Short-circuit return value. Either false or a URL string.
* @param int $id Post ID, or 0 for the current post.
* @param string $context The context for the link. One of 'post' or 'query',
* @param bool $allow_slugs Whether to allow post slugs in the shortlink.
*/
$shortlink = apply_filters( 'pre_get_shortlink', false, $id, $context, $allow_slugs );
if ( false !== $shortlink ) {
return $shortlink;
}
$post_id = 0;
if ( 'query' == $context && is_singular() ) {
$post_id = get_queried_object_id();
$post = get_post( $post_id );
} elseif ( 'post' == $context ) {
$post = get_post( $id );
if ( ! empty( $post->ID ) )
$post_id = $post->ID;
}
$shortlink = '';
// Return p= link for all public post types.
if ( ! empty( $post_id ) ) {
$post_type = get_post_type_object( $post->post_type );
if ( 'page' === $post->post_type && $post->ID == get_option( 'page_on_front' ) && 'page' == get_option( 'show_on_front' ) ) {
$shortlink = home_url( '/' );
} elseif ( $post_type->public ) {
$shortlink = home_url( '?p=' . $post_id );
}
}
/**
* Filters the shortlink for a post.
*
* @since 3.0.0
*
* @param string $shortlink Shortlink URL.
* @param int $id Post ID, or 0 for the current post.
* @param string $context The context for the link. One of 'post' or 'query',
* @param bool $allow_slugs Whether to allow post slugs in the shortlink. Not used by default.
*/
return apply_filters( 'get_shortlink', $shortlink, $id, $context, $allow_slugs );
}
Cвязанные функции
Из метки: permalink (постоянные ссылки ЧПУ)
Еще из раздела: Остальное
wp_get_shortlink 8 комментов
• @ Владимир cайт: tech-repair.ru
Решил написать карту сайта, как простой "выводник" всех постов в виде: название, как кликабельная ссылка с полным путём, затем короткая ссылка сама себе анкор.
<?php
/*
Template Name: Sitemap-shortlinks
*/
?>
<h3>Карта сайта </h3>
<?php query_posts('showposts=500'); ?>
<ul>
<?php while (have_posts()) : the_post(); ?>
<li>
<a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
</li>
<li>
<a href="<?php echo wp_get_shortlink(the_post()); ?>"><?php echo the_title(wp_get_shortlink(the_post())); ?></a>
</li>
<?php endwhile;?>
</ul>
Получаю: короткие ссылки вставляются на разных шагах цикла, т.е. текст короткой ссылки один, сама ссылка другая, а статья, куда она должна вести, третья. Что не так?
Ответить5.8 лет назад #
• Станислав
Доброго времени суток. Подскажите пожалуйста, как можно убрать из короткой ссылки протокол? (-http) Спасибо.
Ответить1.6 года назад #
• Станислав
Решил свой вопрос правкой файла движка. Другого аналога пока что не нашёл.
Возможно кому то тоже понадобиться.
$shortlink = preg_replace("(^https?://)", "", $shortlink);
Ответить1.6 года назад #
• Kama5089
Так ведь фильтр же есть, зачем файл движка трогать?
Вот такой код в тему или плагин:
add_filter('get_shortlink', function($url){
return preg_replace('~^https?://~', '', $url );
});
Ответить1.6 года назад #
• @ campusboy2683 cайт: www.youtube.com/c/wpplus
Перед выводом надо пропускать через esc_url()? Постоянно проблема определить, надо или нет smile
• @ campusboy2683 cайт: www.youtube.com/c/wpplus
В движке везде чиститься или через esc_attr() или esc_url(). Поторопился с вопросом.
• Ольга
Подскажите,пожалуйста, а если страница с шортлинком не перенаправляет на основную страницу, в результате получается полный дубль, который не индексируется поискавиками, но все же присутствует?
Ответитьмесяц назад #
• @ campusboy2683 cайт: www.youtube.com/c/wpplus
Здравствуйте, Ольга. Убедитесь, что страница опубликована, а не находится в черновиках. Только что проверил на чистом тестовом WordPress - перенаправление происходит автоматически. Так же попробуйте зайти на такую страницу как неавторизованный пользователь, будет ли 404 ошибка?
1
Ответитьмесяц назад #
Здравствуйте, !
Ваш комментарий
Предпросмотр | __label__pos | 0.536338 |
Solve java.lang.OutOfMemoryError : unable to create new native Thread - Xss JVM option
Contents of page >
• 1) What is java.lang.OutOfMemoryError : unable to create new native Thread ?
• 2) Solving OutOfMemoryError : unable to create new native Thread ?
• 3) How to use Using the VM (virtual machine) option ss?
• Examples of using -Xss
• 4) What happens if value of -Xss set is too high?
• 5) Program which throws java.lang.OutOfMemoryError : unable to create new native Thread
• 6) Xss option is also known as >
• 7) Default Values of -Xss for different platforms >
• 8) Every thread has its own stack >
• 9) How stack frames are created when thread calls new method?
• 10) Let’s learn how can we reduce the stack size?
• What does thread stack contains?
• Does stack stores/contains object OR what stack doesn’t contains?
• What does heap contains?
1) What is java.lang.OutOfMemoryError : unable to create new native Thread ?
When JVM don’t have enough memory/space to create new thread it throws OutOfMemoryError : unable to create new native Thread.
Also read : Read in detail about : OutOfMemoryError in java
2) Solving OutOfMemoryError : unable to create new native Thread ?
You can resolve “java.lang.OutOfMemoryError : unable to create new native Thread” by setting the appropriate size using -Xss vm option.
Solution 1 to “java.lang.OutOfMemoryError : unable to create new native Thread” >
Try to increase the the -Xss value so that new threads gets enough stack space.
Solution 2 to “java.lang.OutOfMemoryError : unable to create new native Thread” >
Alternatively you could also increase the heap size available using -Xms and -Xmx options and then try to increase and set appropriate -Xss value.
3) How to use Using the VM (virtual machine) option ss?
We can use the VM option ss to adjust the maximum stack size.
VM option is passed using -X followed by your VM option. So, passing ss with -X forms -Xss.
Examples of using -Xss
Pass memory value you want to allocate to thread stack with -Xss.
Example1 of using -Xss >
java -Xss512 MyJavaProgram
It will set the default stack size of JVM to 512 bytes.
Example2 of using -Xss >
java -Xss512k MyJavaProgram
It will set the default stack size of JVM to 512 kilobytes.
Example3 of using -Xss >
java -Xss512m MyJavaProgram
It will set the default stack size of JVM to 512 megabytes.
Example4 of using -Xss >
java -Xss1g MyJavaProgram
It will set the default stack size of JVM to 1 gigabyte.
4) What happens if value of -Xss set is too high?
Setting excessive value of -Xss parameter could cause StackOverFlowError in java.
5) Program which throws java.lang.OutOfMemoryError : unable to create new native Thread
/**
*
* Write a program which could throw
* java.lang.OutOfMemoryError : unable to create new native Thread
*
*/
public class OutOfMemoryErrorUnableToCreateNewNativeThreadExample {
public static void main(String[] args) {
//start/spawn infinite Threads
while(true){
final int i=0;
new Thread(new Runnable(){
public void run() {
System.out.println(Math.random() +" ");
try {
Thread.sleep(10000000);
} catch(InterruptedException e) { }
}
}).start(); //When JVM don’t have enough space to create new thread it
throws OutOfMemoryError : unable to create new native Thread
}
}
}
In the above program we are spawning infinite Threads.
In while loop we are starting threads and putting them to sleep for a long time, so that the threads don’t die. (Learn thread states in java)
After certain time JVM won’t have enough space to create new thread and throw OutOfMemoryError : unable to create new native Thread.
Note : As above program will throw OutOfMemoryError : unable to create new native Thread. So, executing above program might make your system to hang as it will run out of memory.
Output of above >
Exception in thread "main" java.lang.OutOfMemoryError: unable to create new native thread
at java.lang.Thread.start0(Native Method)
at java.lang.Thread.start(Unknown Source)
at infiniteThreads.main(infiniteThreads.java:19)
6) -Xss option is also known as >
Also you must know that -Xss option is same as -XX:ThreadStackSize
7) Default Values of -Xss for different platforms >
For windows 32 bit its 64 KB.
For linux 32 bit its 128 KB.
For windows 64 bit its 128 KB.
For linux 64 bit its 256 KB.
For Solaris Sparc it’s 512KB.
8) Every thread has its own stack >
You must know that each and every thread has its own stack, which makes the methods thread-safe as well.
9) How stack frames are created when thread calls new method?
As we know each and every thread has its own stack. Whenever new method is called new stack frame is created and it is pushed on top of that thread's stack.
10) Let’s learn how can we reduce the stack size?
Before answering this question that how can we reduce the stack size, I’ll like like to discuss few basics what stack and heap can contain >
What does thread stack contains?
The stack contain
• All the local variables,
• All the parameters,
• All the return address.
Does stack stores/contains object OR what stack doesn’t contains?
Stack never stores object, but it stores object reference.
What does heap contains?
Heap contains objects.
Heap even contains arrays because arrays are objects.
So, now let’s learn how can we reduce the stack size. We can try to group all the local variables and parameters in object so that only reference to the object stays on stack, which in turn will help us in reducing the stack space occupied,
Summary -
So in this core java tutorial we learned What is java.lang.OutOfMemoryError : unable to create new native Thread ? How to Solve OutOfMemoryError : unable to create new native Thread. How to use Use the VM (virtual machine) option ss. Examples of using -Xss. Program which throws java.lang.OutOfMemoryError : unable to create new native Thread.
Having any doubt? or you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.
RELATED LINKS>
What are Minor, Major and Full garbage collection in JVM in java
JVM Heap memory (Hotspot heap structure) with diagram in java
What are Young, Old (tenured) and Permanent Generation in JVM in java
Most important and frequently used VM (JVM) PARAMETERS with examples in JVM Heap memory in java
What are -Xms and -Xmx JVM parameters in java, And differences between them with examples
Must read for you : | __label__pos | 0.812075 |
5. Spider
Spider #
Spider是爬虫程序的入口,它将Item、Middleware、Request、等模块组合在一起,从而为你构造一个稳健的爬虫程序。你只需要关注以下两个函数:
• Spider.start:爬虫的启动函数
• parse:爬虫的第一层解析函数,继承Spider的子类必须实现这个函数
Core arguments #
Spider.start的参数如下:
• after_start:爬虫启动后的钩子函数
• before_stop:爬虫启动前的钩子函数
• middleware:中间件类,可以是一个中间件Middleware()实例,也可以是一组Middleware()实例组成的列表
• loop:事件循环
Usage #
import aiofiles
from ruia import AttrField, TextField, Item, Spider
class HackerNewsItem(Item):
target_item = TextField(css_select='tr.athing')
title = TextField(css_select='a.storylink')
url = AttrField(css_select='a.storylink', attr='href')
async def clean_title(self, value):
return value
class HackerNewsSpider(Spider):
start_urls = ['https://news.ycombinator.com/news?p=1', 'https://news.ycombinator.com/news?p=2']
async def parse(self, response):
async for item in HackerNewsItem.get_items(html=await response.text()):
yield item
async def process_item(self, item: HackerNewsItem):
"""Ruia build-in method"""
async with aiofiles.open('./hacker_news.txt', 'a') as f:
await f.write(str(item.title) + '\n')
if __name__ == '__main__':
HackerNewsSpider.start()
How It Works? #
Spider会自动读取start_urls列表里面的请求链接,然后维护一个异步队列,使用生产消费者模式进行爬取,爬虫程序一直循环直到没有调用函数为止 | __label__pos | 0.53313 |
Management
The Management application is where you perform your run time configuration of Siren Investigate, including both the initial setup and ongoing configuration of index patterns, advanced settings that tweak the behaviors of Siren Investigate itself, and the various "objects" that you can save throughout Siren Investigate such as entity tables and searches, visualizations, and dashboards.
Entity tables
To use Siren Investigate, you have connect to the Elasticsearch indices that you want to explore, by configuring one or more entity tables.
For more information, see Creating entity tables.
You can also:
• Create scripted fields that are computed on the fly from your data. You can browse and visualize scripted fields, but you cannot search them.
• Set advanced options such as the number of rows to show in a table and how many of the most popular fields to show. Note: Use caution when modifying advanced options, as it is possible to set values that are incompatible with one another.
• Configure Siren Investigate for a production environment.
Elasticsearch supports the ability to run search and aggregation requests across multiple clusters using a module called cross-cluster search.
Siren Federate does not currently support cross-cluster search.
To take advantage of cross-cluster search, you must configure your Elasticsearch clusters accordingly. Refer to the corresponding Elasticsearch documentation before attempting to use cross-cluster search in Siren Investigate.
After your Elasticsearch clusters are configured for cross-cluster search, you can create specific index patterns in Siren Investigate to search across the clusters of your choosing. Using the same syntax that you would use in a raw cross-cluster search request in Elasticsearch, create your index pattern in Siren Investigate with the convention <cluster-names>:<pattern>.
For example, if you want to query logstash indices across two of the Elasticsearch clusters that you set up for cross-cluster search, which were named cluster_one and cluster_two, you would use cluster_one:logstash-*,cluster_two:logstash-* as your index pattern in Siren Investigate.
Just like in raw search requests in Elasticsearch, you can use wildcards in your cluster names to match any number of clusters, so if you wanted to search logstash indices across any clusters named cluster_foo, cluster_bar, and so on, you would use cluster_*:logstash-* as your index pattern in Siren Investigate.
If you want to query across all Elasticsearch clusters that have been configured for cross cluster search, then use a standalone wildcard for your cluster name in your Siren Investigate index pattern: *:logstash-*.
After an index pattern is configured using the cross-cluster search syntax, all searches and aggregations using that index pattern in Siren Investigate take advantage of cross-cluster search.
Advanced settings for relations
From the Relations tab of the Data model app, click Edit (the pencil icon) next to a relation and then click on Advanced settings (the gear icon) to edit the advanced settings for each relation.
Click on Save relation (the blue button) to save the relation.
The following settings are available:
• Join type: You can choose an automatic join type or select from a hash join, a broadcast join, or an index join.
• Relation join task timeout: You can set the maximum time spent by each join task for that relation in milliseconds. After the timeout has expired, the task passes the documents accumulated at that point on to the next task.
This is a per-task time limit and as each join contains several tasks, the overall response to the request can be a number of multiples of the joinTaskTimeout.
As a semi-join, these documents will be filtered based on the presence of a non-empty value for the join field in the other index pattern in the relation.
The index pattern in question is then filtered by the values returned.
Setting the limit here to -1 here sets the limit to the default siren:joinTaskTimeout set in the Advanced Settings and setting the limit to 0 here removes the limit entirely.
Join types
Siren Federate provides four types of join algorithms. The plugin tries to pick the best algorithm for a given join automatically. However, you can force the selection by choosing one of the available options:
• HASH_JOIN
• BROADCAST_JOIN
• INDEX_JOIN
• ROUTING_JOIN
A detailed description of each algorithm can be found in the Siren Federate plugin documentation.
Minimizing expensive queries
Dashboards connected to large datasets can produce queries that are expensive to process if the operation on the data does not limit the data being queried, for example, when a filter is removed or a broad time range is set.
To help prevent this, some limits can be set on the entity tables and the associated dashboards.
To set the limits, go to the Data model app, select the entity table or search to limit, then go to the Options tab.
For example, the time range of the search might be limited to the last thirty days. An associated dashboard can only be navigated to if there are fewer than five thousand documents, but there are no limits on the number of documents that the dashboard can display.
Users can be permitted to override warnings by setting the investigate override expensive queries limits permission in the ACL plugin. If permitted, the warnings will still be displayed but the user will be able to explicitly allow the operation.
Limit time range
For time based indices, the maximum time range can be defined. Setting a longer time range will be prevented by the system and a warning will be displayed.
Limit the maximum number of documents per dashboard
The maximum number of documents that can be displayed on a dashboard can be set. If the filters are changed to show a larger number of documents, the system will not allow the operation and show a warning.
Limit the maximum number of documents on the dashboards in a join operation
If you attempt to make a join between two dashboards by using the relational navigator and the number of documents on one or both of the dashboards exceeds the limit, the navigation is prevented and a warning message is displayed. Expensive Join Warning
Datasources
For an overview of datasources, see Siren Investigate datasource configuration.
Managing fields
The fields for the index pattern are listed in a table. Click a column header to sort the table by that column. Click Controls in the rightmost column for a given field to edit the field’s properties. You can manually set the field’s format from the Format box. Format options vary based on the field’s type.
You can also set the field’s popularity value in the Popularity text entry box to any desired value. Click Update Field to confirm your changes or Cancel to return to the list of fields.
Siren Investigate has field formatters for the following field types:
String field formatters
String fields support the String and URL formatters.
The String field formatter can apply the following transformations to the field’s contents:
• Convert to lowercase.
• Convert to uppercase.
• Convert to title case.
• Apply the short dots transformation, which replaces the content before a . character with the first character of that content, as in the following example:
Original
Becomes
com.organizations.project.ClassName
c.o.p.ClassName
The URL field formatter can take on the following types:
• The Link type turn the contents of the field into a URL.
• The Image type can be used to specify an image folder where a specified image is located.
You can customize either type of URL field formats with templates. A URL template enables you to add specific values to a partial URL. Use the string {{value}} to add the contents of the field to a fixed URL.
For example, when:
• A field contains a user ID.
• That field uses the URL field formatter.
• The URI template is http://company.net/profiles?user_id={{value}}.
The resulting URL replaces {{value}} with the user ID from the field.
The {{value}} template string URL-encodes the contents of the field. When a field encoded into a URL contains non-ASCII characters, these characters are replaced with a % character and the appropriate hexadecimal code. For example, field contents users/admin result in the URL template adding users%2Fadmin.
When the formatter type is set to Image, the {{value}} template string specifies the name of an image at the specified URI.
To pass unescaped values directly to the URL, use the {{rawValue}} string.
A Label Template enables you to specify a text string that displays instead of the raw URL. You can use the {{value}} template string normally in label templates. You can also use the {{url}} template string to display the formatted URL.
Date field formatters
Date fields support the Date, Url, and String formatters.
The Date formatter enables you to choose the display format of date stamps using the moment.js standard format definitions.
The String field formatter can apply the following transformations to the field’s contents:
• Convert to lowercase
• Convert to uppercase
• Convert to title case
• Apply the short dots transformation, which replaces the content before a . character with the first character of that content, as in the following example:
Original
Becomes
com.organizations.project.ClassName
c.o.p.ClassName
The URL field formatter can take on the following types:
• The Link type turn the contents of the field into a URL.
• The Image type can be used to specify an image folder where a specified image is located.
You can customize either type of URL field formats with templates. A URL template enables you to add specific values to a partial URL. Use the string {{value}} to add the contents of the field to a fixed URL.
For example, when:
• A field contains a user ID.
• That field uses the URL field formatter.
• The URI template is http://company.net/profiles?user_id={{value}}.
The resulting URL replaces {{value}} with the user ID from the field.
The {{value}} template string URL-encodes the contents of the field. When a field encoded into a URL contains non-ASCII characters, these characters are replaced with a % character and the appropriate hexadecimal code. For example, field contents users/admin result in the URL template adding users%2Fadmin.
When the formatter type is set to Image, the {{value}} template string specifies the name of an image at the specified URI.
To pass unescaped values directly to the URL, use the {{rawValue}} string.
A Label Template enables you to specify a text string that displays instead of the raw URL. You can use the {{value}} template string normally in label templates. You can also use the {{url}} template string to display the formatted URL.
Geographic point field formatters
Geographic point fields support the String formatter.
The String field formatter can apply the following transformations to the field’s contents:
• Convert to lowercase
• Convert to uppercase
• Convert to title case
• Apply the short dots transformation, which replaces the content before a . character with the first character of that content, as in the following example:
Original
Becomes
com.organizations.project.ClassName
c.o.p.ClassName
Numeric field formatters
Numeric fields support the URL, Bytes, Duration, Number, Percentage, String, and Color formatters.
The URL field formatter can take on the following types:
• The Link type turn the contents of the field into a URL.
• The Image type can be used to specify an image folder where a specified image is located.
You can customize either type of URL field formats with templates. A URL template enables you to add specific values to a partial URL. Use the string {{value}} to add the contents of the field to a fixed URL.
For example, when:
• A field contains a user ID
• That field uses the URL field formatter
• The URI template is http://company.net/profiles?user_id={{value}}
The resulting URL replaces {{value}} with the user ID from the field.
The {{value}} template string URL-encodes the contents of the field. When a field encoded into a URL contains non-ASCII characters, these characters are replaced with a % character and the appropriate hexadecimal code. For example, field contents users/admin result in the URL template adding users%2Fadmin.
When the formatter type is set to Image, the {{value}} template string specifies the name of an image at the specified URI.
To pass unescaped values directly to the URL, use the {{rawValue}} string.
A Label Template enables you to specify a text string that displays instead of the raw URL. You can use the {{value}} template string normally in label templates. You can also use the {{url}} template string to display the formatted URL.
The String field formatter can apply the following transformations to the field’s contents:
• Convert to lowercase
• Convert to uppercase
• Convert to title case
• Apply the short dots transformation, which replaces the content before a . character with the first character of that content, as in the following example:
Original
Becomes
com.organizations.project.ClassName
c.o.p.ClassName
The Duration field formatter can display the numeric value of a field in the following increments:
• Picoseconds
• Nanoseconds
• Microseconds
• Milliseconds
• Seconds
• Minutes
• Hours
• Days
• Weeks
• Months
• Years
You can specify these increments with up to 20 decimal places for both input and output formats. The default number of decimals for the Number format is 3, i.e. 0,0.[000]. If there are values smaller than this, but larger than 1e-7, they will be rounded to 0. The fix is to change the Numeral.js format pattern to: 0,0.[0000000]
The Color field formatter enables you to specify colors with specific ranges of values for a numeric field.
When you select the Color field formatter, Siren Investigate displays the Range, Font Color, Background Color, and Example fields.
Click Add Color to add a range of values to associate with a particular color. You can click in the Font Color and Background Color fields to display a color picker. You can also enter a specific hex code value in the field. The effect of your current color choices are displayed in the Example field.
image
The Bytes, Number, and Percentage formatters enable you to choose the display formats of numbers in this field using the numeral.js standard format definitions.
Scripted fields
Scripted fields compute data on the fly from the data in your Elasticsearch indices. Scripted field data is shown on the Discover tab as part of the document data, and you can use scripted fields in your visualizations. Scripted field values are computed at query time so they are not indexed and cannot be searched. Note that Siren Investigate cannot query scripted fields.
Computing data on the fly with scripted fields can be very resource intensive and can have a direct impact on Siren Investigate’s performance. Keep in mind that there’s no built-in validation of a scripted field. If your scripts are buggy, you will get exceptions whenever you try to view the dynamically generated data.
When you define a scripted field in Siren Investigate, you have a choice of scripting languages. Starting with 5.0, the default options are Lucene expressions and Painless. While you can use other scripting languages if you enable dynamic scripting for them in Elasticsearch, this is not recommended because they cannot be sufficiently sandboxed.
You can reference any single value numeric field in your expressions, for example:
doc['field_name'].value
For more background on scripted fields and additional examples, refer to Using Painless in Kibana scripted fields.
Creating a scripted field
1. Go to Settings > Indices.
2. Select the index pattern you want to add a scripted field to.
3. Go to the pattern’s Scripted Fields tab.
4. Click Add Scripted Field.
5. Enter a name for the scripted field.
6. Enter the expression that you want to use to compute a value on the fly from your index data.
7. Click Save Scripted Field.
For more information about scripted fields in Elasticsearch, see Scripting.
Modifying a scripted field
1. Go to Settings > Indices
2. Click Edit for the scripted field you want to change.
3. Make your changes and then click Save Scripted Field to update the field.
Deleting a scripted field
1. Go to Settings > Indices.
2. Click Delete for the scripted field you want to remove.
3. Confirm that you really want to remove the field.
Setting advanced options
The Advanced Settings page enables you to directly edit settings that control the behavior of the Siren Investigate application. For example, you can change the format used to display dates, specify the default index pattern, and set the precision for displayed decimal values.
1. Go to Management > Advanced Settings.
2. Click Edit for the option you want to modify.
3. Enter a new value for the option.
4. Click Save.
Modifying the following settings can significantly affect Siren Investigate’s performance and cause problems that are difficult to diagnose. Setting a property’s value to a blank field will revert to the default behavior, which may not be compatible with other configuration settings. Deleting a custom setting removes it from Siren Investigate permanently.
Table 1. Common settings
Name Description Example
sentinl:experimental
Enable experimental features in Siren Alert.
false
default:highlight-type
Sets the default highlighter type for highlighted query matches. Siren Investigate applies Lucene highlighter methods to compute how the highlighting is applied to the text. The two types of highlighter are unified and plain. For more information, see the Elasticsearch documentation.
unified
query:queryString:options
Options for the Lucene query string parser.
{ "analyze_wildcard": true }
sort:options
Options for the Elasticsearch sort parameter.
{ "unmapped_type": "boolean" }
dateFormat
The format to use for displaying formatted dates.
DD/MM/YYYY
dateFormat:tz
The timezone that Siren Investigate uses. The default value of Browser uses the timezone detected by the browser.
Browser
dateFormat:scaled
These values define the format used to render ordered time-based data. Formatted timestamps must adapt to the interval between measurements. Keys are ISO8601 intervals.
[ ["", "HH:mm:ss.SSS"], ["PT1S", "HH:mm:ss"], ["PT1M", "HH:mm"], ["PT1H", "YYYY-MM-DD HH:mm"], ["P1DT", "YYYY-MM-DD"], ["P1YT", "YYYY"] ]
dateFormat:dow
This property defines what day weeks should start on.
Sunday
defaultColumns
Default is _source. Defines the columns that appear by default on the Discover page.
_source
metaFields
An array of fields outside of _source. Siren Investigate merges these fields into the document when displaying the document.
_source, _id, _type, _index, _score
discover:sampleSize
The number of rows to show in the Discover table.
50
discover:aggs:terms:size
Determines how many terms will be visualized when clicking the "visualize" button, in the field boxes, in the discover sidebar. The default value is 20.
20
doc_table:highlight
Highlight results in Discover and Saved Searches Dashboard. Highlighting makes request slow when working on big documents. Set this property to false to switch off highlighting.
true
doc_table:highlight:all_fields
Improves highlighting by using a separate highlight_query that uses all_fields mode on query_string queries. Set to false if you are using a default_field in your index.
true
courier:maxSegmentCount
Siren Investigate splits requests in the Discover page into segments to limit the size of requests sent to the Elasticsearch cluster. This setting constrains the length of the segment list. Long segment lists can significantly increase request processing time.
30
courier:ignoreFilterIfFieldNotInIndex
Set this property to true to skip filters that apply to fields that do not exist in a visualization’s index. Useful when dashboards consist of visualizations from multiple index patterns.
false
fields:popularLimit
This setting governs how many of the top most popular fields are shown.
10
histogram:barTarget
When date histograms use the auto interval, Siren Investigate attempts to generate this number of bars.
50
histogram:maxBars
Date histograms are not generated with more bars than the value of this property, scaling values when necessary.
100
visualization:tileMap:maxPrecision
The maximum geohash precision displayed on tile maps: 7 is high, 10 is very high, 12 is the maximum. Explanation of cell dimensions.
7
visualization:tileMap:WMSdefaults
Default properties for the WMS map server support in the coordinate map.
{ "enabled": false, "url": "https://basemap.nationalmap.gov/arcgis/services/USGSTopo/MapServer/WMSServer", "options": { "version": "1.3.0", "layers": "0", "format": "image/png", "transparent": true, "attribution": "Maps provided by USGS", "styles": "" } }
visualization:regionMap:showWarnings
Whether the region map shows a warning when terms cannot be joined to a shape on the map.
true
visualization:colorMapping
Maps values to specified colors within visualizations.
{"Count":"#6eadc1"}
visualization:loadingDelay
Time to wait before dimming visualizations during query.
2s
visualization:dimmingOpacity
When part of a visualization is highlighted, by moving the mouse pointer over it for example, this is the opacity applied to the other elements. A higher number means other elements will be less opaque.
0.5
csv:separator
A string that serves as the separator for exported values.
,
csv:quoteValues
Set this property to true to quote exported values.
true
history:limit
In fields that have history, such as query inputs, the value of this property limits how many recent values are shown.
10
shortDots:enable
Set this property to true to shorten long field names in visualizations. For example, instead of foo.bar.baz, show f.b.baz.
false
truncate:maxHeight
This property specifies the maximum height that a cell occupies in a table. A value of 0 switches off truncation.
115
format:defaultTypeMap
A map of the default format name for each field type. Field types that are not explicitly mentioned use "default".
{ "ip": { "id": "ip", "params": {} }, "date": { "id": "date", "params": {} }, "number": { "id": "number", "params": {} }, "boolean": { "id": "boolean", "params": {} }, "source": { "id": "_source", "params": {} }, "_default": { "id": "string", "params": {} } }
format:number:defaultPattern
Default numeral format for the "number" format.
0,0.[000]
format:bytes:defaultPattern
Default http://numeraljs.com/[numeral format] numeral format for the "bytes" format.
0,0.[000]b
format:percent:defaultPattern
Default http://numeraljs.com/[numeral format] numeral format for the "percent" format.
0,0.[000]%
format:currency:defaultPattern
Default http://numeraljs.com/[numeral format] numeral format for the "currency" format.
($0,0.[00])
savedObjects:perPage
The number of objects shown on each page of the list of saved objects. The default value is 5.
5
savedObjects:listingLimit
Number of objects to fetch for the listing pages.
1000
timepicker:timeDefaults
The default time filter selection.
{ "from": "now-15m", "to": "now", "mode": "quick" }
timepicker:refreshIntervalDefaults
The time filter’s default refresh interval.
{ "display": "Off", "pause": false, "value": 0 }
dashboard:defaultDarkTheme
Set this property to true to make new dashboards use the dark theme by default.
false
filters:pinnedByDefault
Set this property to true to make filters have a global state by default.
false
filterEditor:suggestValues
Set this property to true to have the filter editor suggest values for fields, instead of providing only a text input. This may result in heavy queries to Elasticsearch.
false
notifications:banner
You can specify a custom banner to display temporary notices to all users. This field supports Markdown.
notifications:lifetime:banner
Specifies the duration in milliseconds for banner notification displays. The default value is 3000000. Set this field to Infinity to switch off banner notifications.
3000000
notifications:lifetime:error
Specifies the duration in milliseconds for error notification displays. The default value is 300000. Set this field to Infinity to switch off error notifications.
300000
notifications:lifetime:warning
Specifies the duration in milliseconds for warning notification displays. The default value is 10000. Set this field to Infinity to switch off warning notifications.
10000
notifications:lifetime:info
Specifies the duration in milliseconds for information notification displays. The default value is 5000. Set this field to Infinity to switch off information notifications.
5000
metrics:max_buckets
The maximum numbers of buckets that cannot be exceeded. For example, this can arise when the user selects a short interval like (for example 1s) for a long time period (for example 1 year).
2000
state:storeInSessionStorage
[experimental] Siren Investigate tracks UI state in the URL, which can lead to problems when there is a lot of information there and the URL gets very long. Enabling this will store parts of the state in your browser session instead, to keep the URL shorter.
true
indexPattern:placeholder
The placeholder for the field "Index name or pattern" in the "Settings > Indices" tab.
logstash-*
context:defaultSize
The number of surrounding entries to show in the context view.
5
context:step
The step size to increment or decrement the context size by.
5
context:tieBreakerFields
A comma-separated list of fields to use for tie breaking between documents that have the same timestamp value. From this list the first field that is present and sortable in the current index pattern is used.
_doc
timelion:showTutorial
Set this property to true to show the Timelion tutorial to users when they first open Timelion.
false
timelion:es.timefield
Default field containing a timestamp when using the .es() query.
@timestamp
timelion:es.default_index
Default index when using the .es() query.
_all
timelion:target_buckets
Used for calculating automatic intervals in visualizations, this is the number of buckets to try to represent.
200
timelion:max_buckets
Used for calculating automatic intervals in visualizations, this is the maximum number of buckets to represent.
2000
timelion:default_columns
The default number of columns to use on a Timelion sheet.
2
timelion:default_rows
The default number of rows to use on a Timelion sheet.
2
Table 2. Siren Investigate settings
Name Description Example
siren:timePrecision
Set to generate time filters with certain precision; possible values are: y, M, w, d, h, m, s, ms. It is set to m (minute) by default, to make the best use of Federate cache on time-based data. However, if the data is updated live and better precision is needed, it can be set to s (second) or ms (millisecond).
s
siren:joinTaskTimeout
Default timeout for join task in milliseconds. Join tasks will return the results gathered at that point when the timeout expires. Set to 0 to disable the global timeout. Can be overwritten per relation in each relation’s advanced options in the relational panel.
0
siren:panel_vertical_size
Set to change the default vertical panel size.
3
siren:vertical_grid_resolution
Set to change vertical grid resolution.
100
siren:enableAllRelBtnCounts
Enable counts on all relational buttons.
true
siren:defaultDashboardld
The dashboard that is displayed when clicking the Dashboard tab for the first time.
null
siren:excludedIndices
A comma separated list of indices / patterns to exclude when performing searches against wildcard patterns.
.kibi*, .siren*, .searchguard, .security, .monitoring*, watcher_alarms-*
siren:graphStatesLimit
Set how many undo/redo steps you want to maintain in memory
10
siren:graphExpansionLimit
Limit the number of elements to retrieve during the graph expansion.
500
siren:graphMaxConcurrentCalls
Limit the number of concurrent calls done by the Graph Browser.
15
siren:countFetchingStrategyDashboards
Strategy for fetching dashboard counts. The parameters instruct the count manager how to issue queries to Elasticsearch; this is used to improve performance when indices contain very large numbers of documents.name - Any string batchSize - how many counts to request in a single query retryOnError - how many retry attempts to make if any requests fail parallelRequests - how many requests to send together at any given time
{ "name": "default", "batchSize": 2, "retryOnError": 1, "parallelRequests": 1 }
siren:countFetchingStrategyRelationalFilters
Strategy for fetching counts for relational filters. Parameters are the same as for countFetchingStrategyDashboards. If the name in both is the same, the count manager will mix the queries for counts on dashboards and relational buttons together.
{ "name": "default", "batchSize": 2, "retryOnError": 1, "parallelRequests": 1 }
siren:showIntroVideos
Enable introductory videos.
true
siren:elasticsearch:searchErrorTrace
Return stack_trace in search or msearch error responses if true.
true
siren:autoRelations:shardTimeout
Milliseconds reserved for computing a single Fingerprints/Relations Wizard request. Requests will return the results gathered at that point when the timeout expires, possibly leading to suboptimal overall results. It does not apply to virtual indices.
5000
Managing entity tables, visualizations, and dashboards
You can view, edit, and remove entity tables, visualizations, and dashboards from Settings > Objects. You can also export or import sets of entity tables, visualizations, and dashboards.
Viewing a saved object displays the selected item in the Discover, Visualize, or Dashboard page. To view a saved object:
1. Go to Management > Saved Objects.
2. Select the object you want to view.
3. Click the View button.
Editing a saved object enables you to directly modify the object definition. You can change the name of the object, add a description, and modify the JSON that defines the object’s properties.
If you attempt to access an object whose index has been removed, Siren Investigate displays its Edit Object page. You can:
• Recreate the index so you can continue using the object.
• Remove the object and recreate it using a different index.
• Change the index pattern to match new index by editing indexPattern.pattern to point to an existing index pattern. This is useful if the index you were working with has been renamed.
No validation is performed for object properties. Submitting invalid changes will render the object unusable. Generally, you should use the Discover, Visualize, or Dashboard pages to create new objects instead of directly editing existing ones.
To edit a saved object:
1. Go to Management > Saved Objects.
2. Select the object you want to edit.
3. Click the Edit button.
4. Make your changes to the object definition.
5. Click the Save Object button.
To remove a saved object:
1. Go to Management > Saved Objects.
2. Select the object you want to remove.
3. Click Delete.
4. Confirm that you really want to remove the object.
To export a set of objects:
1. Go to Management > Saved Objects.
2. Select the type of object you want to export. You can export a set of dashboards, entity tables, or visualizations.
3. Click the selection box for the objects you want to export, or click the Select All box.
4. To export the selected objects without their dependant saved objects, click Export. To attach the dependent saved object(s) click Export with dependencies.
5. Select a location to write the exported JSON.
If dashboards are exported without dependencies, they do not include their associated index patterns, visualizations or any other objects. Recreate these objects manually before importing saved dashboards to a Siren Investigate instance running on another Elasticsearch cluster. To include all objects, click Export with dependencies.
To import a set of objects that doesn’t exist in your connected Elasticsearch cluster:
1. Go to Management > Saved Objects.
2. Click Import to navigate to the JSON file representing the set of objects to import.
3. Click Open after selecting the JSON file.
To import a set of objects that already exist in Elasticsearch cluster:
1. Go to Management > Saved Objects.
2. Click Import to navigate to the JSON file representing the set of objects to import.
3. Click Open after selecting the JSON file.
4. In the Duplicates Saved Objects Found modal, the following options can be chosen:
• Overwrite all existing objects with imported objects - This would update all objects in the Elasticsearch with the imported objects
• Do not overwrite existing objects - This would ignore the duplicate objects from the imported set of objects. Only the new objects will be imported.
• Decide for each object - Here we can decide for each duplicate object from the imported set of objects whether to choose the Existing object in the Elasticsearch or the Imported Object.
5. Click Confirm to import the selected objects.
Adding custom icon packs
You can import custom icons into the application, see Adding custom icons. | __label__pos | 0.740774 |
LibreOffice Module xmerge (master) 1
SxcDocumentDeserializer.java
Go to the documentation of this file.
1 /*
2 * This file is part of the LibreOffice project.
3 *
4 * This Source Code Form is subject to the terms of the Mozilla Public
5 * License, v. 2.0. If a copy of the MPL was not distributed with this
6 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
7 *
8 * This file incorporates work covered by the following license notice:
9 *
10 * Licensed to the Apache Software Foundation (ASF) under one or more
11 * contributor license agreements. See the NOTICE file distributed
12 * with this work for additional information regarding copyright
13 * ownership. The ASF licenses this file to you under the Apache
14 * License, Version 2.0 (the "License"); you may not use this file
15 * except in compliance with the License. You may obtain a copy of
16 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
17 */
18
19 package org.openoffice.xmerge.converter.xml.sxc;
20
21 import java.io.IOException;
22 import java.util.Iterator;
23
32 import org.w3c.dom.Element;
33 import org.w3c.dom.Node;
34 import org.w3c.dom.NodeList;
35
47 public abstract class SxcDocumentDeserializer implements OfficeConstants,
49
53 private SpreadsheetDecoder decoder = null;
54
56 private org.w3c.dom.Document settings = null;
57
59 private org.w3c.dom.Document doc = null;
60
62 private final ConvertData cd ;
63
65 private StyleCatalog styleCat = null;
66
67 private int textStyles = 1;
68 private int colStyles = 1;
69 private int rowStyles = 1;
70
77 this.cd = cd;
78 }
79
91 public abstract SpreadsheetDecoder createDecoder(String workbook, String[] worksheetNames, String password)
92 throws IOException;
93
108 protected abstract String getWorkbookName(ConvertData cd) throws IOException;
109
118 protected abstract String[] getWorksheetNames(ConvertData cd) throws IOException;
119
135 IOException {
136
137 // Get the name of the WorkBook from the ConvertData.
138 String[] worksheetNames = getWorksheetNames(cd);
139 String workbookName = getWorkbookName(cd);
140
141 // Create a document
142 SxcDocument sxcDoc = new SxcDocument(workbookName);
143 sxcDoc.initContentDOM();
144 sxcDoc.initSettingsDOM();
145
146 // Default to an initial 5 entries in the catalog.
147 styleCat = new StyleCatalog(5);
148
149 doc = sxcDoc.getContentDOM();
150 settings = sxcDoc.getSettingsDOM();
151 initFontTable();
152 // Little fact for the curious reader: workbookName should
153 // be the name of the StarCalc file minus the file extension suffix.
154
155 // Create a Decoder to decode the DeviceContent to a spreadsheet document
156 // ToDo - we aren't using a password in StarCalc, so we can
157 // use any value for password here. If StarCalc XML supports
158 // passwords in the future, we should try to get the correct
159 // password value here.
160
161 decoder = createDecoder(workbookName, worksheetNames, "password");
162
163 Debug.log(Debug.TRACE, "<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
164 Debug.log(Debug.TRACE, "<DEBUGLOG>");
165
166 decoder.addDeviceContent(cd);
167 decode();
168
169 Debug.log(Debug.TRACE, "</DEBUGLOG>");
170
171 return sxcDoc;
172 }
173
178 private void initFontTable() {
179
180 String fontTable[]= new String[] { "Tahoma", "Tahoma", "swiss", "variable",
181 "Courier New", "'Courier New'",
182 "modern", "fixed" };
183 // Traverse to the office:body element.
184 // There should only be one.
185 NodeList list = doc.getElementsByTagName(TAG_OFFICE_FONT_DECLS);
186 Node root = list.item(0);
187
188 for(int i=0;i<fontTable.length;) {
189
190 // Create an element node for the table
191 Element tableElement = doc.createElement(TAG_STYLE_FONT_DECL);
192
193 tableElement.setAttribute(ATTRIBUTE_STYLE_NAME, fontTable[i++]);
194 tableElement.setAttribute(ATTRIBUTE_FO_FONT_FAMILY, fontTable[i++]);
195 tableElement.setAttribute(ATTRIBUTE_FO_FONT_FAMILY_GENERIC, fontTable[i++]);
196 tableElement.setAttribute(ATTRIBUTE_STYLE_FONT_PITCH, fontTable[i++]);
197
198 root.appendChild(tableElement);
199 }
200
201 }
202
208 protected void decode() throws IOException {
209
210 // Get number of worksheets
211 int numSheets = decoder.getNumberOfSheets();
212 // #i33702# - check for an Empty InputStream.
213 if(numSheets == 0)
214 {
215 System.err.println("Error decoding invalid Input stream");
216 return;
217 }
218
219 // Traverse to the office:body element.
220 // There should only be one.
221 NodeList list = doc.getElementsByTagName(TAG_OFFICE_BODY);
222 Node node = list.item(0);
223
224 for (int i = 0; i < numSheets; i++) {
225
226 // Set the decoder to the correct worksheet
227 decoder.setWorksheet(i);
228
229 int len = list.getLength();
230
231 if (len > 0) {
232
233 // Process the spreadsheet
234 processTable(node);
235 }
236 }
237
238 // Add the Defined Name table if there is one
239 Iterator<NameDefinition> nameDefinitionTable = decoder.getNameDefinitions();
240 if(nameDefinitionTable.hasNext()) {
241 processNameDefinition(node, nameDefinitionTable);
242 }
243
244 // add settings
245 NodeList settingsList = settings.getElementsByTagName(TAG_OFFICE_SETTINGS);
246 Node settingsNode = settingsList.item(0);
247 processSettings(settingsNode);
248
249 }
250
258 protected void processSettings(Node root) {
259
260 Element configItemSetEntry = settings.createElement(TAG_CONFIG_ITEM_SET);
261 configItemSetEntry.setAttribute(ATTRIBUTE_CONFIG_NAME, "view-settings");
262 Element configItemMapIndexed = settings.createElement(TAG_CONFIG_ITEM_MAP_INDEXED);
263 configItemMapIndexed.setAttribute(ATTRIBUTE_CONFIG_NAME, "Views");
264 Element configItemMapEntry = settings.createElement(TAG_CONFIG_ITEM_MAP_ENTRY);
265 BookSettings bs = decoder.getSettings();
266 bs.writeNode(settings, configItemMapEntry);
267
268 configItemMapIndexed.appendChild(configItemMapEntry);
269 configItemSetEntry.appendChild(configItemMapIndexed);
270 root.appendChild(configItemSetEntry);
271 }
272
283 protected void processNameDefinition(Node root, Iterator<NameDefinition> eNameDefinitions) throws IOException {
284
285 Debug.log(Debug.TRACE, "<NAMED-EXPRESSIONS>");
286
287 Element namedExpressionsElement = doc.createElement(TAG_NAMED_EXPRESSIONS);
288
289 while(eNameDefinitions.hasNext()) {
290
291 NameDefinition tableEntry = eNameDefinitions.next();
292 tableEntry.writeNode(doc, namedExpressionsElement);
293 }
294
295 root.appendChild(namedExpressionsElement);
296
297 Debug.log(Debug.TRACE, "</NAMED-EXPRESSIONS>");
298 }
299
312 protected void processTable(Node root) throws IOException {
313
314 Debug.log(Debug.TRACE, "<TABLE>");
315
316 // Create an element node for the table
317 Element tableElement = doc.createElement(TAG_TABLE);
318
319 // Get the sheet name
320 String sheetName = decoder.getSheetName();
321
322 // Set the table name attribute
323 tableElement.setAttribute(ATTRIBUTE_TABLE_NAME, sheetName);
324
325 // ToDo - style currently hardcoded - get real value
326 // Set table style-name attribute
327 tableElement.setAttribute(ATTRIBUTE_TABLE_STYLE_NAME, "Default");
328
329 // Append the table element to the root node
330 root.appendChild(tableElement);
331
332 Debug.log(Debug.TRACE, "<SheetName>" + sheetName + "</SheetName>");
333
334 // Add the various different table-columns
335 processColumns(tableElement);
336
337 // Get each cell and add to doc
338 processCells(tableElement);
339
340 Debug.log(Debug.TRACE, "</TABLE>");
341 }
342
355 protected void processColumns(Node root) throws IOException {
356
357 for(Iterator<ColumnRowInfo> e = decoder.getColumnRowInfos();e.hasNext();) {
358
359 ColumnRowInfo ci = e.next();
360 if(ci.isColumn()) {
362 SxcConstants.DEFAULT_STYLE, ci.getSize(), null);
363
364 Style result[] = styleCat.getMatching(cStyle);
365 String styleName;
366 if(result.length==0) {
367
368 cStyle.setName("co" + colStyles++);
369 styleName = cStyle.getName();
370 Debug.log(Debug.TRACE,"No existing style found, adding " + styleName);
371 styleCat.add(cStyle);
372 } else {
373 ColumnStyle existingStyle = (ColumnStyle) result[0];
374 styleName = existingStyle.getName();
375 Debug.log(Debug.TRACE,"Existing style found : " + styleName);
376 }
377
378 // Create an element node for the new row
379 Element colElement = doc.createElement(TAG_TABLE_COLUMN);
380 colElement.setAttribute(ATTRIBUTE_TABLE_STYLE_NAME, styleName);
381 if(ci.getRepeated()!=1) {
382 String repeatStr = String.valueOf(ci.getRepeated());
383 colElement.setAttribute(ATTRIBUTE_TABLE_NUM_COLUMNS_REPEATED, repeatStr);
384 }
385 root.appendChild(colElement);
386 }
387 }
388 }
389
402 protected void processCells(Node root) throws IOException {
403
404 // The current row element
405 Element rowElement = null;
406
407 // The current cell element
408 Element cellElement = null;
409
410 // The row number - we may not have any rows (empty sheet)
411 // so set to zero.
412 int row = 0;
413
414 // The column number - This is the expected column number of
415 // the next cell we are reading.
416 int col = 1;
417
418 // The number of columns in the spreadsheet
419 int lastColumn = decoder.getNumberOfColumns();
420
421 Node autoStylesNode = null;
422
423 // Loop over all cells in the spreadsheet
424 while (decoder.goToNextCell()) {
425
426 // Get the row number
427 int newRow = decoder.getRowNumber();
428
429 // Is the cell in a new row, or part of the current row?
430 if (newRow != row) {
431
432 // Make sure that all the cells in the previous row
433 // have been entered.
434 if (col <= lastColumn && rowElement != null) {
435 int numSkippedCells = lastColumn - col + 1;
436 addEmptyCells(numSkippedCells, rowElement);
437 }
438
439 // log an end row - if we already have a row
440 if (row != 0) {
441 Debug.log(Debug.TRACE, "</tr>");
442 }
443
444 // How far is the new row from the last row?
445 int deltaRows = newRow - row;
446
447 // Check if we have skipped any rows
448 if (deltaRows > 1) {
449 // Add in empty rows
450 addEmptyRows(deltaRows-1, root, lastColumn);
451 }
452
453 // Re-initialize column (since we are in a new row)
454 col = 1;
455
456 // Create an element node for the new row
457 rowElement = doc.createElement(TAG_TABLE_ROW);
458
459 for(Iterator<ColumnRowInfo> e = decoder.getColumnRowInfos();e.hasNext();) {
460 ColumnRowInfo cri = e.next();
461 if(cri.isRow() && cri.getRepeated()==newRow-1) {
462 // We have the correct Row BIFFRecord for this row
463 RowStyle rStyle = new RowStyle("Default",SxcConstants.ROW_STYLE_FAMILY,
464 SxcConstants.DEFAULT_STYLE, cri.getSize(), null);
465
466 Style result[] = styleCat.getMatching(rStyle);
467 String styleName;
468 if(result.length==0) {
469
470 rStyle.setName("ro" + rowStyles++);
471 styleName = rStyle.getName();
472 Debug.log(Debug.TRACE,"No existing style found, adding " + styleName);
473 styleCat.add(rStyle);
474 } else {
475 RowStyle existingStyle = (RowStyle) result[0];
476 styleName = existingStyle.getName();
477 Debug.log(Debug.TRACE,"Existing style found : " + styleName);
478 }
479 rowElement.setAttribute(ATTRIBUTE_TABLE_STYLE_NAME, styleName);
480 // For now we will not use the repeat column attribute
481 }
482 }
483
484 // Append the row element to the root node
485 root.appendChild(rowElement);
486
487 // Update row number
488 row = newRow;
489
490 Debug.log(Debug.TRACE, "<tr>");
491 }
492
493 if (rowElement == null) {
494 //utterly busted
495 break;
496 }
497
498 // Get the column number of the current cell
499 int newCol = decoder.getColNumber();
500
501 // Check to see if some columns were skipped
502 if (newCol != col) {
503
504 // How many columns have we skipped?
505 int numColsSkipped = newCol - col;
506
507 addEmptyCells(numColsSkipped, rowElement);
508
509 // Update the column number to account for the
510 // skipped cells
511 col = newCol;
512 }
513
514 // Lets start dealing with the cell data
515 Debug.log(Debug.TRACE, "<td>");
516
517 // Get the cell's contents
518 String cellContents = decoder.getCellContents();
519
520 // Get the type of the data in the cell
521 String cellType = decoder.getCellDataType();
522
523 // Get the cell format
524 Format fmt = decoder.getCellFormat();
525
526 // Create an element node for the cell
527 cellElement = doc.createElement(TAG_TABLE_CELL);
528
529 Node bodyNode = doc.getElementsByTagName(TAG_OFFICE_BODY).item(0);
530
531 // Not every document has an automatic style tag
532 autoStylesNode = doc.getElementsByTagName(
534
535 if (autoStylesNode == null) {
536 autoStylesNode = doc.createElement(TAG_OFFICE_AUTOMATIC_STYLES);
537 doc.insertBefore(autoStylesNode, bodyNode);
538 }
539
540 CellStyle tStyle = new
542 SxcConstants.DEFAULT_STYLE, fmt, null);
543 String styleName;
544 Style result[] = styleCat.getMatching(tStyle);
545 if(result.length==0) {
546
547 tStyle.setName("ce" + textStyles++);
548 styleName = tStyle.getName();
549 Debug.log(Debug.TRACE,"No existing style found, adding " + styleName);
550 styleCat.add(tStyle);
551 } else {
552 CellStyle existingStyle = (CellStyle) result[0];
553 styleName = existingStyle.getName();
554 Debug.log(Debug.TRACE,"Existing style found : " + styleName);
555 }
556
557 cellElement.setAttribute(ATTRIBUTE_TABLE_STYLE_NAME, styleName);
558
559 // Store the cell data into the appropriate attributes
560 processCellData(cellElement, cellType, cellContents);
561
562 // Append the cell element to the row node
563 rowElement.appendChild(cellElement);
564
565 // Append the cellContents as a text node
566 Element textElement = doc.createElement(TAG_PARAGRAPH);
567 cellElement.appendChild(textElement);
568 textElement.appendChild(doc.createTextNode(cellContents));
569
570 Debug.log(Debug.TRACE, cellContents);
571 Debug.log(Debug.TRACE, "</td>");
572
573 // Increment to the column number of the next expected cell
574 col++;
575 }
576
577 // Make sure that the last row is padded correctly
578 if (col <= lastColumn && rowElement != null) {
579 int numSkippedCells = lastColumn - col + 1;
580 addEmptyCells(numSkippedCells, rowElement);
581 }
582
583 // Now write the style catalog to the document
584 if(autoStylesNode!=null) {
585 Debug.log(Debug.TRACE, "Well the autostyle node was found!!!");
586 NodeList nl = styleCat.writeNode(doc, "dummy").getChildNodes();
587 int nlLen = nl.getLength(); // nl.item reduces the length
588 for (int i = 0; i < nlLen; i++) {
589 autoStylesNode.appendChild(nl.item(0));
590 }
591 }
592
593 if (row != 0) {
594 // The sheet does have rows, so write out a /tr
595 Debug.log(Debug.TRACE, "</tr>");
596 }
597 }
598
613 protected void addEmptyRows(int numEmptyRows, Node root, int numEmptyCells) {
614
615 // Create an element node for the row
616 Element rowElement = doc.createElement(TAG_TABLE_ROW);
617
618 // ToDo - style currently hardcoded - get real value
619 // Set row style-name attribute
620 rowElement.setAttribute(ATTRIBUTE_TABLE_STYLE_NAME, "Default");
621
622 // Set cell number-rows-repeated attribute
623 rowElement.setAttribute(ATTRIBUTE_TABLE_NUM_ROWS_REPEATED,
624 Integer.toString(numEmptyRows));
625
626 // Append the row element to the root node
627 root.appendChild(rowElement);
628
629 // Open Office requires the empty row to have an empty cell (or cells)
630 addEmptyCells(numEmptyCells, rowElement);
631
632 // Write empty rows to the log
633 for (int i = 0; i < numEmptyRows; i++) {
634 Debug.log(Debug.TRACE, "<tr />");
635 }
636
637 }
638
652 protected void addEmptyCells(int numColsSkipped, Node row) {
653
654 // Create an empty cellElement
655 Element cellElement = doc.createElement(TAG_TABLE_CELL);
656
657 // ToDo - style currently hardcoded - get real value
658 // Set cell style-name attribute
659 cellElement.setAttribute(ATTRIBUTE_TABLE_STYLE_NAME, "Default");
660
661 // If we skipped more than 1 cell, we must set the
662 // appropriate attribute
663 if (numColsSkipped > 1) {
664
665 // Set cell number-columns-repeated attribute
666 cellElement.setAttribute(ATTRIBUTE_TABLE_NUM_COLUMNS_REPEATED,
667 Integer.toString(numColsSkipped));
668 }
669
670 // Append the empty cell element to the row node
671 row.appendChild(cellElement);
672
673 // Write empty cells to the log
674 for (int i = 0; i < numColsSkipped; i++) {
675 Debug.log(Debug.TRACE, "<td />");
676 }
677 }
678
689 protected void processCellData(Element cellElement, String type,
690 String contents) {
691
692 // Set cell value-type attribute
693 cellElement.setAttribute(ATTRIBUTE_TABLE_VALUE_TYPE, type);
694
695 // Does the cell contain a formula?
696 if (contents.startsWith("=")) {
697
698 cellElement.setAttribute(ATTRIBUTE_TABLE_FORMULA, contents);
699
700 cellElement.setAttribute(ATTRIBUTE_TABLE_VALUE, decoder.getCellValue());
701 // String data does not require any additional attributes
702 } else if (!type.equals(CELLTYPE_STRING)) {
703
704 if (type.equals(CELLTYPE_TIME)) {
705
706 // Data returned in StarOffice XML format, so store in
707 // attribute
708 cellElement.setAttribute(ATTRIBUTE_TABLE_TIME_VALUE,
709 contents);
710
711 } else if (type.equals(CELLTYPE_DATE)) {
712
713 // Data returned in StarOffice XML format, so store in
714 // attribute
715 cellElement.setAttribute(ATTRIBUTE_TABLE_DATE_VALUE,
716 contents);
717
718 } else if (type.equals(CELLTYPE_BOOLEAN)) {
719
720 // StarOffice XML format requires stored boolean value
721 // to be in lower case
722 cellElement.setAttribute(ATTRIBUTE_TABLE_BOOLEAN_VALUE,
723 contents.toLowerCase());
724
725 } else if (type.equals(CELLTYPE_CURRENCY)) {
726 // TODO - StarOffice XML format requires a correct style to
727 // display currencies correctly. Need to implement styles.
728 // TODO - USD is for US currencies. Need to pick up
729 // the correct currency location from the source file.
730 cellElement.setAttribute(ATTRIBUTE_TABLE_CURRENCY, "USD");
731
732 // Data comes stripped of currency symbols
733 cellElement.setAttribute(ATTRIBUTE_TABLE_VALUE, contents);
734
735 } else if (type.equals(CELLTYPE_PERCENT)) {
736 // Data comes stripped of percent signs
737 cellElement.setAttribute(ATTRIBUTE_TABLE_VALUE, contents);
738
739 } else {
740 // Remaining data types use table-value attribute
741
742 cellElement.setAttribute(ATTRIBUTE_TABLE_VALUE, contents);
743 }
744 }
745 }
746 }
abstract String getCellContents()
Return the contents of the active cell.
void addEmptyRows(int numEmptyRows, Node root, int numEmptyCells)
This method will add empty rows to the.
void addEmptyCells(int numColsSkipped, Node row)
This method will add empty cells to the.
String CELLTYPE_STRING
The cell contains data of type string.
String ATTRIBUTE_TABLE_VALUE_TYPE
Attribute tag for table:value-type of element table:table-cell.
abstract int getNumberOfColumns()
Returns the number of populated columns in the current WorkSheet.
void setName(String newName)
Sets the name of this.
Definition: Style.java:125
abstract Iterator< ColumnRowInfo > getColumnRowInfos()
Returns an Enumeration to a Vector of.
String ATTRIBUTE_TABLE_DATE_VALUE
Attribute tag for table:date-value of element table:table-cell.
String TAG_TABLE_ROW
Element tag for table:table-row.
String TAG_CONFIG_ITEM_MAP_INDEXED
Element tag for config:config-item-map-indexed.
abstract String[] getWorksheetNames(ConvertData cd)
This method will return the name of the WorkSheet from the.
abstract Iterator< NameDefinition > getNameDefinitions()
Returns an Enumeration to a Vector of.
Provides general purpose utilities.
void initFontTable()
This initializes a font table so we can include some basic font support for spreadsheets.
String TAG_STYLE_FONT_DECL
Element tag for style:font-decl.
void processCellData(Element cellElement, String type, String contents)
This method process the data in a cell and sets the appropriate attributes on the cell...
String ATTRIBUTE_TABLE_CURRENCY
Attribute tag for table:currency of element table:table-cell.
static void log(int flag, String msg)
Log message based on the flag type.
Definition: Debug.java:205
void processTable(Node root)
This method process a WorkSheet and generates a portion of the.
String TAG_CONFIG_ITEM_SET
Element tag for config:config-item-set.
String ATTRIBUTE_TABLE_STYLE_NAME
Attribute tag for table:style-name of table elements.
This is a class representing the different attributes for a worksheet contained in settings...
String ATTRIBUTE_STYLE_NAME
Attribute tag for style:name of element style:name.
int getSize()
Get the height (for rows) or width (for columns).
This interface contains constants for StarOffice XML tags, attributes (StarCalc cell types...
void decode()
Outer level method used to decode a WorkBook into a.
abstract String getWorkbookName(ConvertData cd)
This method will return the name of the WorkBook from the.
String ATTRIBUTE_TABLE_TIME_VALUE
Attribute tag for table:time-value of element table:table-cell.
String DEFAULT_STYLE
Name of the default style.
String TAG_TABLE_COLUMN
Element tag for table:table-column.
abstract void addDeviceContent(ConvertData cd)
Add the contents of a.
This is a class to define a Name Definition structure.
static final int TRACE
Trace messages.
Definition: Debug.java:46
Interface defining constants for Sxc attributes.
String TAG_OFFICE_FONT_DECLS
Element tag for office:font-decls.
String ATTRIBUTE_TABLE_NAME
Attribute tag for table:name of element table:table.
String CELLTYPE_BOOLEAN
The cell contains data of type boolean.
String ATTRIBUTE_TABLE_BOOLEAN_VALUE
Attribute tag for table:time-boolean-value of element table:table-cell.
String TAG_TABLE_CELL
Element tag for table:table-cell.
exports com.sun.star. java
abstract String getCellValue()
Return the value of the active cell.
abstract String getCellDataType()
Return the data type of the active cell.
String ATTRIBUTE_FO_FONT_FAMILY_GENERIC
Attribute tag for fo:font-family of element fo:font-family.
void add(Node node, String families[], Class<?> classes[], Class<?> defaultClass, boolean alwaysCreateDefault)
Parse the.
int i
This class specifies the format for a given spreadsheet cell.
Definition: Format.java:26
String CELLTYPE_DATE
The cell contains data of type date.
String TAG_CONFIG_ITEM_MAP_ENTRY
Element tag for config:config-item-map-entry.
String ATTRIBUTE_TABLE_NUM_ROWS_REPEATED
Attribute tag for table:number-rows-repeated of element table:table-row.
abstract BookSettings getSettings()
Returns the.
String ATTRIBUTE_FO_FONT_FAMILY
Attribute tag for fo:font-family of element fo:font-family.
abstract SpreadsheetDecoder createDecoder(String workbook, String[] worksheetNames, String password)
This.
String TAG_OFFICE_AUTOMATIC_STYLES
Element tag for office:automatic-styles.
abstract String getSheetName()
Returns the name of the current WorkSheet.
String COLUMN_STYLE_FAMILY
Family name for column styles.
void writeNode(org.w3c.dom.Document doc, Node root)
Writes out a content.xml entry for this NameDefinition object.
String ATTRIBUTE_TABLE_VALUE
Attribute tag for table:value of element table:table-cell.
String TABLE_CELL_STYLE_FAMILY
Family name for table-cell styles.
This is a class to define a table-column structure.
String ROW_STYLE_FAMILY
Family name for row styles.
void processSettings(Node root)
This method process the settings portion of the.
void processNameDefinition(Node root, Iterator< NameDefinition > eNameDefinitions)
This method process a Name Definition Table and generates a portion of the.
String TAG_NAMED_EXPRESSIONS
Element tag for table:named-expression.
abstract int getRowNumber()
Returns the number of the active row.
String ATTRIBUTE_TABLE_NUM_COLUMNS_REPEATED
Attribute tag for table:number-columns-repeated of element table:table-cell.
String ATTRIBUTE_TABLE_FORMULA
Attribute tag for table:formula of element table:table-cell.
String ATTRIBUTE_CONFIG_NAME
Attribute tag for config:name of element config:config-item.
String CELLTYPE_PERCENT
The cell contains data of type percent.
String ATTRIBUTE_STYLE_FONT_PITCH
Attribute tag for style:font-pitch of element style:font-pitch.
String CELLTYPE_TIME
The cell contains data of type time.
Any result
Provides interfaces for converting between two.
Definition: Convert.java:19
This class is used for logging debug messages.
Definition: Debug.java:39
void processCells(Node root)
This method process the cells in a.
int getRepeated()
Get the repeat count for this item.
void processColumns(Node root)
This method process the cells in a.
abstract int getNumberOfSheets()
Returns the total number of sheets in the WorkBook.
String TAG_OFFICE_BODY
Element tag for office:body.
Element writeNode(org.w3c.dom.Document parentDoc, String name)
Create a.
This is an interface used by the DiffAlgorithm and MergeAlgorithm to access a.
Definition: Iterator.java:27
abstract int getColNumber()
Returns the number of the active column.
This class is an implementation of.
String CELLTYPE_CURRENCY
The cell contains data of type currency.
String TAG_OFFICE_SETTINGS
Element tag for office:settings.
abstract boolean goToNextCell()
Move on the next populated cell in the current WorkSheet.
abstract void setWorksheet(int sheetIndex)
Sets the active WorkSheet.
void writeNode(org.w3c.dom.Document settings, Node root)
Writes out a settings.xml entry for this.
String getName()
Returns the name of this.
Definition: Style.java:116 | __label__pos | 0.927528 |
How to trigger ctrl+c when clicking on image?
I want to trigger ctrl +c copy and ctrl +vcommand when I click of images, can you suggest how to achieve?
Hi @Chandishwar,
what do you mean with images? Do you mean the symbols itself?
You could use the normal CopyPaste module to use it’s copy and paste functionalities on an element.click event. So something like
var eventBus = modeler.get('eventBus'),
copyPaste = modeler.get('copyPaste');
eventBus.on('element.click', function(event) {
var element = event.element
// use copyPaste.copy + copyPaste.paste to copy/paste the element
});
Thanks for the inputs, | __label__pos | 1 |
Go Down
Topic: Interrupt funtion with delay() (Read 46623 times) previous topic - next topic
Palmer
I just got my Arduino Duemilanove last week and have been toying with it daily with no major confusion until today.
I set up 4 LED's in digital 4-7, a button on digital 3 and a pot on analog 0.
The pot is mapped to 0-16 and the number is output in binary on the LEDs.
The button should do a mini-knight rider effect, but it seems to crash at the call of delay(100); and not do anything until I reset.
Is there some rule against using a delay in an interrupt call?
If so, why does delayMicroseconds() work? (not good for me who needs a longer delay though)
Code: [Select]
int oldPot = 0;
int val;
int potVal;
int k;
void setup(){
DDRD = DDRD | B11110000;
PORTD = PORTD ^ B11110000;
attachInterrupt(1, krider, FALLING);
}
void loop(){
potVal = map(analogRead(0), 0, 1023, 0, 15);
if(oldPot != potVal){
PORTD = B11110000 & (~potVal << 4);
oldPot = potVal;
val = potVal;
}
}
void krider(){
for(int i = 0; i < 4; i++){
k = 1 << i;
PORTD = B11110000 & (~k << 4);
delay(100);
}
for(int i = 3; i >= 0; i--){
k = 1 << i;
PORTD = B11110000 & (~k << 4);
delay(100);
}
}
Any other tips and advice would be appreciated too :)
SteelToad
You don't need that k variable
for (i=1; i<=8; i=(i<<1))
PORTD = B11110000 & i;
Just out of curiosity, why use an interrupt ?
Could switch bounce be part of your problem. You trigger the interrupt, and then while you're in the delay, a second high signal from the button re-triggers the interrupt ?
bohne
Don't use the delay() function in an interrupt routine!
It relies on interrupts itself.
The delayMicroseconds() function in contrast uses a simple wait loop and disables interrupts before execution (and then restores SREG after execution), so you can use it in interrupt routines.
For details have a look here:
http://code.google.com/p/arduino/source/browse/tags/0015/hardware/cores/arduino/wiring.c
http://www.dorkbot.de
http://www.arduino.cc/cgi-bin/yabb2/YaBB.pl?num=1236434254
http://www.luminet.cc
Palmer
#3
May 02, 2009, 12:03 am Last Edit: May 02, 2009, 12:48 am by Palmer Reason: 1
@Ray: Thanks for the tip :)
And I used an interrupt because I haven't before and thought it was a simple use for one.
I did have to modify the example you gave me to work because of the pins I'm using and had to keep the not in there as I hooked the LED's to come on when the pins go low.
@bohne: Ahh, that'd be why then!
I saw it said that "interrupts will work as they should." but I'm guessing that meant that while it's being delayed an interrupt will work during the delayed period and not the other way.
I also saw it said that more knowledgeable programmers would avoid the use of delay for anything over 10's of seconds. It'd be nice to know how, just for future reference?
srossel
Hi guys!
so, how did you fix it ? can you show us what did you do?
Thank you very much!
Go Up
| __label__pos | 0.802631 |
Introducing Functions
What is a Function?
A function is just a segment of code, separate from the rest of your code. You separate it because it’s nice and handy, and you want to use it not once but over and over. It’s a chunk of code that you think is useful and want to use again. Functions save you from writing the code over and over.
Here’s an example.
Suppose you need to check text from a textbox. You want to trim any blank spaces from the left and right of the text that the user entered. So, if they entered this:
Bill Gates
You want to turn it into this:
Bill Gates
But you also want to check if the user entered any text at all. You don’t want the textbox to be completely blank!
You can use the PHP inbuilt function called trim (). Like this:
$user_text = trim($_POST['text1'] );
That will get rid of the white space in the text box. But it won’t check if the text box is blank. You can add an if statement for that:
if ($user_text == "") {
error_message = "Blank textbox detected";
}
But what if you have lots of textboxes on your form? You’d have to have lots of if statements and check each single variable for a blank string. That’s a lot of code to write!
Rather than do that, you can create a single function, with one if statement that can be used for each blank string you need to check. Using a function means there’s less code for you to write. And it’s more efficient. We’ll see how to write a function for the above scenario in a moment. But first, here’s the basic syntax for a function.
function function_name() {
}
So you start by typing the word function. You then need to come up with a name for your function. You can call almost anything you like. It’s just like a variable name. Next, you type two round brackets ( ). Finally, you need the two curly brackets as well { }.
Whatever you function does goes between the curly brackets. Here’s a simple example that just print something out:
function display_error_message() {
print "Error Detetceted";
}
In the example above, we’ve started with function. We’ve then called this particular function display_error_message. In between the curly brackets, there a print statement.
Try it out with this script:
<?PHP
function display_error_message( ) {
print "Error Detetceted";
}
?>
Run your script and see what happens. You should find that nothing happens!
The reason that nothing happened is because a function is a separate piece of code. It doesn’t run until you tell it to. Just loading the script won’t work. It’s like those inbuilt functions you used, such as trim. You can’t use trim( ) unless you type out the name, and what you want PHP to trim. The same applies to your own functions – you have to “tell” PHP that you want to use a function that you wrote. You do this by simply typing out the name of your function. This is known as “calling” a function.
Try this new version of the script.
<?PHP
function display_error_message() {
print "Error Detetceted";
}
display_error_message( );
?>
After the function, we’ve typed out the name again. This is enough to tell PHP to run our code segment. Now change your code to this, and see what happens:
<?PHP
display_error_message();
function display_error_message() {
print "Error Detetceted";
}
?>
When you run the code, you should see no difference – the function will still get executed with the name above or below the function. But for neatness and readability’s sake, it’s better to put all of your function either at the top or bottom of your scripts. Or better yet, in a separate PHP file. You can then use another inbuilt function called “Include” (which we’ll get to soon).
Defining functions
PHP functions are similar to other programming languages. A function is a piece of code which takes one more input in the form of parameter and does some processing and returns a value.A function is a self-contained block of code that performs a specific task.Functions can either return values when called or can simply perform an operation without returning any value.
Why uses Functions?
• Better code organization: functions allow us to group blocks of related code that perform a specific task together.
• Reusability: once defined, a function can be called by a number of scripts in our PHP files. This saves us time of reinventing the wheel when we want to perform some routine tasks such as connecting to the database
• Easy maintenance: updates to the system only need to be made in one place.
PHP Built-in Functions
A function is a self-contained block of code that performs a specific task.
PHP has a huge collection of internal or built-in functions that you can call directly within your PHP scripts to perform a specific task, like gettype(),print_r(),var_dump, etc.
PHP User-Defined Functions
In addition to the built-in functions, PHP also allows you to define your own functions. It is a way to create reusable code packages that perform specific tasks and can be kept and maintained separately form main program. Here are some advantages of using functions:
• Functions reduces the repetition of code within a program: Function allows you to extract commonly used block of code into a single component. Now you can perform the same task by calling this function wherever you want within your script without having to copy and paste the same block of code again and again.
• Functions makes the code much easier to maintain:Since a function created once can be used many times, so any changes made inside a function automatically implemented at all the places without touching the several files.
• Functions makes it easier to eliminate the errors: When the program is subdivided into functions, if any error occur you know exactly what function causing the error and where to find it. Therefore, fixing errors becomes much easier.
• Functions can be reused in other application: Because a function is separated from the rest of the script, it’s easy to reuse the same function in other applications just by including the php file containing those functions.
A user-defined function declaration starts with the word function:
Syntax:
function functionName () {
//code to be executed;
}
Note: A function name can start with a letter or underscore (not a number).
Creating and Invoking Functions
Its very easy to create your own PHP function. Suppose you want to create a PHP function which will simply write a simple message on your browser when you will call it. Following example creates a function called writeMessage () and then calls it just after creating it.
Note: that while creating a function its name should start with keyword function and all the PHP code should be put inside { and } braces as shown in the following example below:
<html>
<head>
<title>Writing PHP Function</title>
</head>
<body>
<?php
/* Defining a PHP Function */
function writeMessage () {
echo "You are really a nice person, Have a nice time!";
}
/* Calling a PHP Function */
writeMessage ();
?>
</body>
</html>
This is a another simple example of an user-defined function, that display today’s date:
<?php
// Defining function
function whatIsToday(){
echo "Today is " . date('l', mktime());
}
// Calling function
whatIsToday();
?>
Before creating first user defined function, let’s look at the rules that you must follow when creating your own functions:
• Function names must start with a letter or an underscore but not a number
• The function name must be unique
• The function name must not contain spaces
• It is considered a good practice to use descriptive function names.
• Functions can optionally accept parameters and return values too.
Using parameters
PHP gives you option to pass your parameters inside a function. You can pass as many as parameters your like.The parameters work like placeholder variables within a function; they’re replaced at run time by the values (known as argument) provided to the function at the time of invocation.
function myFunc($oneParameter, $anotherParameter){
// Code to be executed
}
You can define as many parameters as you like. However, for each parameter you specify, a corresponding argument needs to be passed to the function when it is called.
Following example takes two integer parameters and add them together and then print them:
<html>
<head>
<title>Writing PHP Function with Parameters</title>
</head>
<body>
<?php
function addFunction($num1, $num2) {
$sum = $num1 + $num2;
echo "Sum of the two numbers is : $sum";
}
addFunction(10, 20);
?>
</body>
</html>
This will display following result:
Sum of the two numbers is: 30
Note: An argument is a value that you pass to a function, and a parameter is the variable within the function that receives the argument. However, in common usage these terms are interchangeable i.e. an argument is a parameter is an argument.
Functions with Optional Parameters and Default Values
The following example shows how to use a default parameter. If we call the function setHeight() without arguments it takes the default value as argument:
<html>
<body>
<?php
function setHeight($minheight = 50) {
echo "The height is : $minheight <br>";
}
setHeight(350);
setHeight();
setHeight(135);
setHeight(80);
?>
</body>
</html>
This will display following result:
The height is: 350
The height is: 50
The height is: 135
The height is: 80
Understanding scope
Scope of a variable is defined as its extent in program within which it can be accessed, i.e. the scope of a variable is the portion of the program with in which it is visible or can be accessed.
Depending on the scopes, there are only two scopes available in PHP namely local and global scopes.Variable scope is known as its boundary within which it can be visible or accessed from code.
• Local variables (local scope)
• Global variables (special global scope)
• Static variables (local scope)
• Function parameters (local scope)
When a variable is accessed outside its scope it will cause PHP error Undefined Variable.
Local variables:
The variables declared within a function are called local variables to that function and has its scope only in that particular function. In simple words it cannot be accessed outside that function. Any declaration of a variable outside the function with same name as that of the one within the function is a complete different variable. We will learn about functions in details in later articles. For now, consider a function as a block of statements.
Example:
<?php
$num = 60;
function local_var()
{
// This $num is local to this function
// the variable $num outside this function
// is a completely different variable
$num = 50;
echo "local num = $num \n";
}
local_var();
// $num outside function local_var() is a
// completely different Variable than that of
// inside local_var()
echo "Variable num outside local_var() is $num \n";
?>
Output:
local num = 50
Variable num outside local_var() is 60
Global variables:
The variables declared outside a function are called global variables. These variables can be accessed directly outside a function. To get access within a function we need to use the “global” keyword before the variable to refer to the global variable.
Example:
<?php
$num = 20;
// function to demonstrate use of global variable
function global_var()
{
// we have to use global keyword before
// the variable $num to access within
// the function
global $num;
echo "Variable num inside function : $num \n";
}
global_var();
echo "Variable num outside function : $num \n";
?>
Output:
Variable num inside function: 20
Variable num outside function: 20
Static variable:
It is the characteristic of PHP to delete the variable, ones it completes its execution and the memory is freed. But sometimes we need to store the variables even after the completion of function execution. To do this we use static keyword and the variables are then called as static variables.
Example:
<?php
// function to demonstrate static variables
function static_var()
{
// static variable
static $num = 5;
$sum = 2;
$sum++;
$num++;
echo $num, "\n";
echo $sum, "\n";
}
// first function call
static_var();
// second function call
static_var();
?>
Output:
6
3
7
3
You must have noticed that $num regularly increments even after the first function call but $sum doesn’t. This is because $sum is not static and its memory is freed after execution of first function call.
Function Parameters (Local Scope)
Function parameters (arguments) are local variables defined within the local scope of the function on which it is used as the argument.
Scope and File Includes
The boundary of file includes does not demarcate the scope of variables. The scope of a variable is only governed by the function block and not based on the file include. A variable can be declared in a PHP file and used in another file by using ‘include’ or ‘require’ that file.
Function Inside Function or Class
Remember that the scope in PHP is governed by a function block. Any new function declared anywhere starts a new scope. If an anonymous function is defined inside another function, the anonymous function has its own local scope.
<?php
function foo() {
$fruit = 'apple';
$bar = function () {
// $fruit cannot be accessed inside here
$animal = 'lion';
};
// $animal cannot be accessed outside here
}
?>
In the above example code, $fruit variable is restricted to the outer function and its scope does not span inside the anonymous inner function. The same way, $animal which is declared inside is not accessible in the outer function as its scope boundary is restricted to the inner function.
Returning values
Values are returned by using the optional return statement. Any type may be returned, including arrays and objects. This causes the function to end its execution immediately and pass control back to the line from which it was called.
Call by Value
Call by value means passing the value directly to a function. The called function uses the value in a local variable; any changes to it do not affect the source variable.PHP allows you to call function by value and reference both.
Let’s understand the concept of call by value by the help of examples.
In this example, variable $str is passed to the adder function where it is concatenated with ‘Call By Value’ string. But, printing $str variable results ‘Hello’ only. It is
because changes are done in the local variable $str2 only. It doesn’t reflect to $str variable.
<?php
function adder($str2)
{
$str2 .= 'Call By Value';
}
$str = 'Hello ';
adder($str);
echo $str;
?>
Call by Reference
In PHP there are two ways you can pass arguments to a function: by value and by reference. By default, function arguments are passed by value so that if the value of the argument within the function is changed, it does not get affected outside of the function. However, to allow a function to modify its arguments, they must be passed by reference.
Passing an argument by reference is done by prepending an ampersand (&) to the argument name in the function definition, as shown in the example below:
<html lang="en">
<head>
<title>PHP Passing Arguments by Reference</title>
</head>
<body>
<?php
/* Defining a function that multiply a number
by itself and return the new value */
function selfMultiply(&$number){
$number *= $number;
return $number;
}
$mynum = 5;
echo $mynum . "<br>"; // Outputs: 5
selfMultiply($mynum);
echo $mynum . "<br>"; // Outputs: 25
?>
</body>
</html>
Output:
5
25
Difference between call by value and call by reference in PHP
• Call by value means passing the value directly to a function. The called function uses the value in a local variable; any changes to it do not affect the source variable.
• Call by reference means passing the address of a variable where the actual value is stored. The called function uses the value stored in the passed address; any changes to it do affect the source variable.
Reusing Codes
In programming, reusable code is the use of similar code in multiple functions.No, not by copying and then pasting the same code from one block to another and from there to another and so on. Instead, code reusability defines the methodology you can use to use similar code, without having to re-write it everywhere. As I have already said, not in a way to copy and paste it.There are many techniques to make code reusable in your applications.
There are several advantages to code reuse and they include: reduces the cost (you will spend more time maintaining your code than writing it, therefore you want to make sure that you limit the number of lines in use.). In simple terms, less code means lower cost. Secondly, there is reliability – existing mature code is always more reliable than a fresh ‘green’ code.
By the help of include and require construct, we can reuse HTML code or PHP script in many PHP scripts.
Implementing recursion
What is Recursion?
The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily.There’s nearly always an end condition of some sort — known as the base case — otherwise the function would continue to call itself indefinitely (or at least until the computer ran out of memory).
In other words, Recursion is a method of solving problems that involves breaking a problem down into smaller and smaller subproblems until you get to a small enough problem that it can be solved trivially. Usually recursion involves a function calling itself. While it may not seem like much on the surface, recursion allows us to write elegant solutions to problems that may otherwise be very difficult to program.
Sometimes a problem is too difficult or too complex to solve because it is too big. If the problem can be broken down into smaller versions of itself, we may be able to find a way to solve one of these smaller versions and then be able to build up to a solution to the entire problem. This is the idea behind recursion; recursive algorithms break down a problem into smaller pieces which you either already know the answer to or can solve by applying the same algorithm to each piece, and then combining the results.
Why Stack Overflow error occurs in recursion?
If base case is not reached or not defined, then stack overflow problem may arise. Let us take an example to understand this.
If fact (10) is called, it will call fact (9), fact (8), fact (7) and so on but number will never reach 100. So, the base case is not reached. If the memory is exhausted by these functions on stack, it will cause stack overflow error.
Care must be taken in PHP, however, as your code must not carry out a certain number of recursive function calls. i.e. There must be a mechanism (IF statement, etc.) that stops the recursion after the desired result has been found. If you allow your function to carry out an unlimited amount of calls you will receive the error: Fatal error: Maximum function nesting level of ‘100’ reached, aborting.
How to implement a recursive function in PHP
In general terms, a recursive function works like this:
• The calling code calls the recursive function.
• The function does any processing or calculations required.
• If the base case has not yet been reached, the function calls itself to continue the recursion. This creates a new instance of the function.
• If the base case is reached, the function just returns control to the code that called it, thereby ending the recursion.
In pseudocode, a simple recursive function looks something like this:
function myRecursiveFunction() {
// (do the required processing...)
if ( baseCaseReached ) {
// end the recursion
return;
} else {
// continue the recursion
myRecursiveFunction();
}
The best way to understand recursive functions is by looking at some practical example. Let’s explore below example that show how recursion works in PHP:
• Factorials
• Checks to see if the number is less than 50
Let’s write a recursive function to calculate the factorial for a given number, n:
<?php
function factorial( $n ) {
// Base case
if ( $n == 0 ) {
echo "Base case: \$n = 0. Returning 1...<br>";
return 1;
}
// Recursion
echo "\$n = $n: Computing $n * factorial( " . ($n-1) . " )...<br>";
$result = ( $n * factorial( $n-1 ) );
echo "Result of $n * factorial( " . ($n-1) . " ) = $result. Returning $result...<br>";
return $result;
}
echo "The factorial of 5 is: " . factorial( 5 );
?>
As you can see, this function is pretty simple. Let’s break it down:
1. Begin the function
function factorial( $n ) {
First, we define the function, factorial (), and include a parameter, $n, to hold the number that we want to calculate the factorial for.
2. Set up the base case
// Base case
if ( $n == 0 ) {
echo "Base case: \$n = 0. Returning 1...<br>";
return 1;
}
Within our function, we first define the base case, which is when the supplied value, $n, equals 0. If this is the case then we’ve reached the end of our recursion, and we simply return 1 (the factorial of 0 is 1). This value is returned to the code that called it, which will be either another instance of the factorial() function, or the outside calling code.
3. Do the recursion
// Recursion
echo "\$n = $n: Computing $n * factorial( " . ($n-1) . " )...<br>";
$result = ( $n * factorial( $n-1 ) );
echo "Result of $n * factorial( " . ($n-1) . " ) = $result. Returning $result...<br>";
return $result;
}
The last block of code in the function performs the actual recursion, and it’s run as long as $n is greater than zero. It calls itself, passing in $n-1 as the argument, and multiplies the resulting value by $n. In other words, it computes the factorial of the integer that is 1 less than the current value, then multiplies this by the current value to get the current value’s factorial. It then stores this value in $result and returns it to the calling code.
4. Test the function
echo "The factorial of 5 is: " . factorial( 5 );
Finally, we test our function by calling it with a value of 5. This produces the correct result (120).
Let’s write a recursive function Checks to see if the number is less than 50:
//Our recursive function.
function recursive($num){
//Print out the number.
echo $num, '<br>';
//If the number is less or equal to 50.
if($num < 50){
//Call the function again. Increment number by one.
return recursive($num + 1);
}
}
//Set our start number to 1.
$startNum = 1;
//Call our recursive function.
recursive($startNum);
The code above is pretty simple. Basically, the function checks to see if the number is less than 50. If the number is less than 50, then we increment the number and call the function again. This process is repeated until the number has reached 50.
Using Require () and include ()
You can include the content of a PHP file into another PHP file before the server executes it. There are two PHP functions which can be used to included one PHP file into another PHP file.
• The include() Function
• The require() Function
This is a strong point of PHP which helps in creating functions, headers, footers, or elements that can be reused on multiple pages. This will help developers to make it easy to change the layout of complete website with minimal effort. If there is any change required then instead of changing thousands of files just change included file.
The include() Function
The include() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the include() function generates a warning but the script will continue execution.
Syntax:
include(File-name);
Example:
include (“header.php”)
Assume you want to create a common menu for your website. Then create a file menu.php with the following content.
<a href="http://www.tutorialspoint.com/index.htm">Home</a> -
<a href="http://www.tutorialspoint.com/ebxml">ebXML</a> -
<a href="http://www.tutorialspoint.com/ajax">AJAX</a> -
<a href="http://www.tutorialspoint.com/perl">PERL</a><br />
Now create as many pages as you like and include this file to create header. For example now your test.php file can have following content.
<html>
<body>
<?php include("menu.php"); ?>
<p>This is an example to show how to include PHP file!</p>
</body>
</html>
It will produce the following result:
The require() Function
The require() function takes all the text in a specified file and copies it into the file that uses the include function. If there is any problem in loading a file then the require() function generates a fatal error and halt the execution of the script.
So there is no difference in require() and include() except they handle error conditions. It is recommended to use the require() function instead of include(), because scripts should not continue executing if files are missing or misnamed.
Syntax:
require(File-name);
Example:
require(“header.php”);
You can try using above example with require() function and it will generate same result. But if you will try following two examples where file does not exist then you will get different results.
<html>
<body>
<?php include("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP file!</p>
</body>
</html>
This will produce the following result:
This is an example to show how to include wrong PHP file!
Now let’s try same example with require() function.
<html>
<body>
<?php require("xxmenu.php"); ?>
<p>This is an example to show how to include wrong PHP file!</p>
</body>
</html>
This time file execution halts and nothing is displayed.
Difference between include() and require() in PHP :
• include() function takes one argument , a path/name of the specified file you want to include.
• require() function performs the similar functionality as include() function, takes one argument i.e. path/name of the file you want to include.
• include() function does not stop execution , just give warning and continues to execute the script in case of file name not found i..e missing/misnamed files .
• require() function gives fatal error if it founds any problem like file not found or misnamed files and stops the execution once get fatal error.
• The require() function is identical to include(), except that it handles errors differently. If an error occurs, the include() function generates a warning, but the script will continue execution. The require() generates a fatal error, and the script will stop.
Array, String, Math, Date functions
Array Functions?
The array functions allow you to access and manipulate arrays.
Simple and multi-dimensional arrays are supported.
Installation
There is no installation needed to use these functions; they are part of the PHP core.
PHP Array Functions
Arrays are essential for storing, managing, and operating on sets of variables.These functions allow you to interact with and manipulate arrays in various ways.
Function Description
array() Creates an array
array_change_key_case() Changes all keys in an array to lowercase or uppercase
array_chunk() Splits an array into chunks of arrays
array_column() Returns the values from a single column in the input array
array_combine() Creates an array by using the elements from one “keys” array and one “values” array
array_count_values() Counts all the values of an array
array_diff() Compare arrays, and returns the differences (compare values only)
array_diff_assoc() Compare arrays, and returns the differences (compare keys and values)
array_diff_key() Compare arrays, and returns the differences (compare keys only)
array_diff_uassoc() Compare arrays, and returns the differences (compare keys and values, using a user-defined key comparison function)
array_diff_ukey() Compare arrays, and returns the differences (compare keys only, using a user-defined key comparison function)
array_fill() Fills an array with values
array_fill_keys() Fills an array with values, specifying keys
array_filter() Filters the values of an array using a call back function
array_flip() Flips/Exchanges all keys with their associated values in an array
array_intersect() Compare arrays, and returns the matches (compare values only)
array_intersect_assoc() Compare arrays and returns the matches (compare keys and values)
array_intersect_key() Compare arrays, and returns the matches (compare keys only)
array_intersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using a user-defined key comparison function)
array_intersect_ukey() Compare arrays, and returns the matches (compare keys only, using a user-defined key comparison function)
array_key_exists() Checks if the specified key exists in the array
array_keys() Returns all the keys of an array
array_map() Sends each value of an array to a user-made function, which returns new values
array_merge() Merges one or more arrays into one array
array_merge_recursive() Merges one or more arrays into one array recursively
array_multisort() Sorts multiple or multi-dimensional arrays
array_pad() Inserts a specified number of items, with a specified value, to an array
array_pop() Deletes the last element of an array
array_product() Calculates the product of the values in an array
array_push() Inserts one or more elements to the end of an array
array_rand() Returns one or more random keys from an array
array_reduce() Returns an array as a string, using a user-defined function
array_replace() Replaces the values of the first array with the values from following arrays
array_replace_recursive() Replaces the values of the first array with the values from following arrays recursively
array_reverse() Returns an array in the reverse order
array_search() Searches an array for a given value and returns the key
array_shift() Removes the first element from an array, and returns the value of the removed element
array_slice() Returns selected parts of an array
array_splice() Removes and replaces specified elements of an array
array_sum() Returns the sum of the values in an array
array_udiff() Compare arrays, and returns the differences (compare values only, using a user-defined key comparison function)
array_udiff_assoc() Compare arrays, and returns the differences (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)
array_udiff_uassoc() Compare arrays, and returns the differences (compare keys and values, using two user-defined key comparison functions)
array_uintersect() Compare arrays, and returns the matches (compare values only, using a user-defined key comparison function)
array_uintersect_assoc() Compare arrays, and returns the matches (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values)
array_uintersect_uassoc() Compare arrays, and returns the matches (compare keys and values, using two user-defined key comparison functions)
array_unique() Removes duplicate values from an array
array_unshift() Adds one or more elements to the beginning of an array
array_values() Returns all the values of an array
array_walk() Applies a user function to every member of an array
array_walk_recursive() Applies a user function recursively to every member of an array
arsort() Sorts an associative array in descending order, according to the value
asort() Sorts an associative array in ascending order, according to the value
compact() Create array containing variables and their values
count() Returns the number of elements in an array
current() Returns the current element in an array
each() Returns the current key and value pair from an array
end() Sets the internal pointer of an array to its last element
extract() Imports variables into the current symbol table from an array
in_array() Checks if a specified value exists in an array
key() Fetches a key from an array
krsort() Sorts an associative array in descending order, according to the key
ksort() Sorts an associative array in ascending order, according to the key
list() Assigns variables as if they were an array
natcasesort() Sorts an array using a case insensitive “natural order” algorithm
natsort() Sorts an array using a “natural order” algorithm
next() Advance the internal array pointer of an array
pos() Alias of current()
prev() Rewinds the internal array pointer
range() Creates an array containing a range of elements
reset() Sets the internal pointer of an array to its first element
rsort() Sorts an indexed array in descending order
shuffle() Shuffles an array
sizeof() Alias of count()
sort() Sorts an indexed array in ascending order
uasort() Sorts an array by values using a user-defined comparison function
uksort() Sorts an array by keys using a user-defined comparison function
usort() Sorts an array using a user-defined comparison function
Math Functions
The math functions can handle values within the range of integer and float types.The PHP math functions are part of the PHP core. No installation is required to use these functions.
The following Math functions are the part of the PHP core so you can use these functions within your script without any further installation.
Function Description
abs() Returns the absolute (positive) value of a number
acos() Returns the arc cosine of a number
acosh() Returns the inverse hyperbolic cosine of a number
asin() Returns the arc sine of a number
asinh() Returns the inverse hyperbolic sine of a number
atan() Returns the arc tangent of a number in radians
atan2() Returns the arc tangent of two variables x and y
atanh() Returns the inverse hyperbolic tangent of a number
base_convert() Converts a number from one number base to another
bindec() Converts a binary number to a decimal number
ceil() Rounds a number up to the nearest integer
cos() Returns the cosine of a number
cosh() Returns the hyperbolic cosine of a number
decbin() Converts a decimal number to a binary number
dechex() Converts a decimal number to a hexadecimal number
decoct() Converts a decimal number to an octal number
deg2rad() Converts a degree value to a radian value
exp() Calculates the exponent of e
expm1() Returns exp(x) – 1
floor() Rounds a number down to the nearest integer
fmod() Returns the remainder of x/y
getrandmax() Returns the largest possible value returned by rand()
hexdec() Converts a hexadecimal number to a decimal number
hypot() Calculates the hypotenuse of a right-angle triangle
is_finite() Checks whether a value is finite or not
is_infinite() Checks whether a value is infinite or not
is_nan() Checks whether a value is ‘not-a-number’
lcg_value() Returns a pseudo random number in a range between 0 and 1
log() Returns the natural logarithm of a number
log10() Returns the base-10 logarithm of a number
log1p() Returns log(1+number)
max() Returns the highest value in an array, or the highest value of several specified values
min() Returns the lowest value in an array, or the lowest value of several specified values
mt_getrandmax() Returns the largest possible value returned by mt_rand()
mt_rand() Generates a random integer using Mersenne Twister algorithm
mt_srand() Seeds the Mersenne Twister random number generator
octdec() Converts an octal number to a decimal number
pi() Returns the value of PI
pow() Returns x raised to the power of y
rad2deg() Converts a radian value to a degree value
rand() Generates a random integer
round() Rounds a floating-point number
sin() Returns the sine of a number
sinh() Returns the hyperbolic sine of a number
sqrt() Returns the square root of a number
srand() Seeds the random number generator
tan() Returns the tangent of a number
tanh() Returns the hyperbolic tangent of a number
Function Description
Function Description
Function Description
Date Functions
The PHP date() function convert a timestamp to a more readable date and time.
The computer stores dates and times in a format called UNIX Timestamp, which measures time as a number of seconds since the beginning of the Unix epoch (midnight Greenwich Mean Time on January 1, 1970 i.e. January 1, 1970 00:00:00 GMT).
Since this is an impractical format for humans to read, PHP converts a timestamp to a format that is readable to humans and dates from your notation into a timestamp the computer understands. The syntax of the PHP date() function can be given with.
date(format, timestamp)
The format parameter in the date () function is required which specifies the format of returned date and time. However, the timestamp is an optional parameter, if not included then current date and time will be used. The following statement displays today’s date:
<?php
$today = date("d/m/Y");
echo $today;
?>
Note: The PHP date() function return the current date and time according to the built-in clock of the web server on which the script has been executed.
Super Global Array Variables
The super global arrays in PHP will help you find cookies information, how to send secure data to server and upload files and create sessions which are variables that store information of user for later use.Super global arrays are predefined arrays and can be accessed anywhere in the page, without using the word global.
These are specially-defined array variables in PHP that make it easy for you to get information about a request or its context.The superglobals are available throughout your script. These variables can be accessed from any function, class or any file without doing any special task such as declaring any global variable etc. They are mainly used to store and get information from one page to another etc. in an application.
Below is the list of super global variables available in PHP:
• $GLOBALS
• $_SERVER
• $_REQUEST
• $_POST
• $_GET
• $_FILES
• $_ENV
• $_COOKIE
• $_SESSION
Let us now learn about some of these superglobals in details:
$GLOBALS:It is a super global variable which is used to access global variables from anywhere in the PHP script. PHP stores all the global variables in array $GLOBALS [] it consists of an array which have an index that holds the global variable name, which can be accessed.
Below program illustrates the use of $GLOBALS in PHP:
<?php
$x = 300;
$y = 200;
function multiplication(){
$GLOBALS['z'] = $GLOBALS['x'] * $GLOBALS['y'];
}
multiplication();
echo $z;
?>
Output:
60000
In the above code two global variables are declared $x and $y which are assigned some value to them. Then a function multiplication() is defined to multiply the values of $x and $y and store in another variable $z defined in the GLOBAL array.
$_SERVER
It is a PHP super global variable that stores the information about headers, paths and script locations. Some of these elements are used to get the information from the super global variable $_SERVER.
Below program illustrates the use of $_SERVER in PHP:
<html>
<body>
<?php
echo $_SERVER['PHP_SELF'];
echo "<br>";
echo $_SERVER['SERVER_NAME'];
echo "<br>";
echo $_SERVER['HTTP_HOST'];
echo "<br>";
echo $_SERVER['HTTP_REFERER'];
echo "<br>";
echo $_SERVER['HTTP_USER_AGENT'];
echo "<br>";
echo $_SERVER['SCRIPT_NAME'];
?>
</body>
</html>
In the above code we used the $_SERVER elements to get some information. We get the current file name which is worked on using PHP_SELF element. Then we get server name used currently using SERVER_NAME element. And then we get the host name through HTTP_HOST.
$_REQUEST
It is a super global variable which is used to collect the data after submitting a HTML form. $_REQUEST is not used mostly, because $_POST and $_GET perform the same task and are widely used.
Below is the HTML and PHP code to explain how $_REQUEST works:
<!DOCTYPE html>
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
NAME: <input type="text" name="fname">
<button type="submit">SUBMIT</button>
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = htmlspecialchars($_REQUEST['fname']);
if(empty($name)){
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
Output:
In the above code we have created a form that takes the name as input from the user and prints its name on clicking of submit button. We transport the data accepted in the form to the same page using $_SERVER[‘PHP_SELF’] element as specified in the action attribute, because we manipulate the data in the same page using the PHP code. The data is retrieved using the $_REQUEST super global array variable
$_POST
It is a super global variable used to collect data from the HTML form after submitting it. When form uses method post to transfer data, the data is not visible in the query string, because of which security levels are maintained in this method.
Below is the HTML and PHP code to explain how $_POST works:
The example below shows a form with an input field and a submit button. When a user submits the data by clicking on “Submit”, the form data is sent to the file specified in the action attribute of the <form> tag. In this example, we point to the file itself for processing form data. If you wish to use another PHP file to process form data, replace that with the filename of your choice. Then, we can use the super global variable $_POST to collect the value of the input field:
<html>
<body>
<form method="post" action="<?php echo $_SERVER['PHP_SELF'];?>">
Name: <input type="text" name="fname">
<input type="submit">
</form>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// collect value of input field
$name = $_POST['fname'];
if (empty($name)) {
echo "Name is empty";
} else {
echo $name;
}
}
?>
</body>
</html>
Output:
$_GET
$_GET is a super global variable used to collect data from the HTML form after submitting it. When form uses method get to transfer data, the data is visible in the query string, therefore the values are not hidden. $_GET super global array variable stores the values that come in the URL.
Below is the HTML and PHP code to explain how $_GET works:
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body bgcolor="cyan">
<?php
$name = $_GET['name'];
$city = $_GET['city'];
echo "<h1>This is ".$name." of ".$city."</h1><br>";
?>
<img src = "2.jpg" alt = "nanilake" height = "400" width="500" />
</body>
</html>
We are actually seeing half of the logic just now. In the above code we have created a hyperlink image of Nainital Lake which will take us to picture. PHP page and with it will also take the paramerters name=Nainilakeand city=Nainital.
That is when we click on the small image of Nainital Lake we will be taken to the next page picture.php along with the parameters. As the default method is get, these parameters will be passed to the next page using get method and they will be visible in the address bar. When we want to pass values to an address they are attached to the address using a question mark (?).
Here the parameter name=Nainilake is attached to the address. If we want to add more values, we can add them using ampersand (&) after every key-value pair similarly as city=Nainital is added using ampersand after the name parameter. Now after clicking on the image of Nainital Lake we want the picture.php page to be displayed with the value of parameter displayed along with it.
Summary
• Functions are blocks of code that perform specific tasks
• Built in functions are functions that are shipped with PHP
• PHP has over 700 built in functions
• User defined functions are functions that you can create yourself to enhance PHP
• Information can be passed to functions through arguments. An argument is just like a variable.
• By the help of include and require construct, we can reuse HTML code or PHP script in many PHP scripts.
• Variable scope is known as its boundary within which it can be visible or accessed from code.
• Super Global Array Variablesare mainly used to store and get information from one page to another etc. in an application.
Apply now for Advanced PHP Training Course
Copyright 1999- Ducat Creative, All rights reserved.
Anda bisa mendapatkan server slot online resmi dan terpercaya tentu saja di sini. Sebagai salah satu provider yang menyediakan banyak pilihan permainan. | __label__pos | 0.92704 |
Commit bd2264ad authored by [email protected]'s avatar [email protected]
Browse files
Mostly comments, following NR/SPJ meeting
parent 11337f44
......@@ -60,7 +60,7 @@ middleLiveness m = middle m
middle (MidAssign lhs expr) = gen expr . kill lhs
middle (MidStore addr rval) = gen addr . gen rval
middle (MidUnsafeCall tgt ress args) = gen tgt . gen args . kill ress
middle (MidAddToContext ra args) = gen ra . gen args
middle (MidAddToContext ra args) = gen ra . gen args
middle (CopyIn _ formals _) = kill formals
middle (CopyOut _ actuals) = gen actuals
......
......@@ -59,27 +59,50 @@ data Answer m l a = Dataflow a | Rewrite (Graph m l)
{-
\subsection {Descriptions of dataflow passes}
============== Descriptions of dataflow passes} ================
\paragraph{Passes for backward dataflow problems}
------ Passes for backward dataflow problemsa
The computation of a fact is the basis of a dataflow pass.
A~computation takes not one but two type parameters:
\begin{itemize}
\item
Type parameter [['i]] is an input, from which it should be possible to
derived a dataflow fact of interest.
For example, [['i]] might be equal to a fact, or it might be a tuple
of which one element is a fact.
\item
Type parameter [['o]] is an output, or possibly a function from
[[fuel]] to an output
\end{itemize}
Backward analyses compute [[in]] facts (facts on inedges).
<<exported types for backward analyses>>=
A computation takes *four* type parameters:
* 'middle' and 'last' are the types of the middle
and last nodes of the graph over which the dataflow
solution is being computed
* 'input' is an input, from which it should be possible to
derive a dataflow fact of interest. For example, 'input' might
be equal to a fact, or it might be a tuple of which one element
is a fact.
* 'output' is an output, or possibly a function from 'fuel' to an
output
A computation is interesting for any pair of 'middle' and 'last' type
parameters that can form a reasonable graph. But it is not useful to
instantiate 'input' and 'output' arbitrarily. Rather, only certain
combinations of instances are likely to be useful, such as those shown
below.
Backward analyses compute *in* facts (facts on inedges).
-}
-- A dataflow pass requires a name and a transfer function for each of
-- four kinds of nodes:
-- first (the BlockId),
-- middle
-- last
-- LastExit
-- A 'BComputation' describes a complete backward dataflow pass, as a
-- record of transfer functions. Because the analysis works
-- back-to-front, we write the exit node at the beginning.
--
-- So there is
-- an 'input' for each out-edge of the node
-- (hence (BlockId -> input) for bc_last_in)
-- an 'output' for the in-edge of the node
data BComputation middle last input output = BComp
{ bc_name :: String
, bc_exit_in :: output
......@@ -93,13 +116,17 @@ data BComputation middle last input output = BComp
-- * A pure transformation computes no facts but only changes the graph.
-- * A fully general pass both computes a fact and rewrites the graph,
-- respecting the current transaction limit.
--
type BAnalysis m l a = BComputation m l a a
type BTransformation m l a = BComputation m l a (Maybe (UniqSM (Graph m l)))
type BFunctionalTransformation m l a = BComputation m l a (Maybe (Graph m l))
-- ToDo: consider replacing UniqSM (Graph l m) with (AGraph m l)
type BPass m l a = BComputation m l a (OptimizationFuel -> DFM a (Answer m l a))
type BUnlimitedPass m l a = BComputation m l a ( DFM a (Answer m l a))
type BUnlimitedPass m l a = BComputation m l a ( DFM a (Answer m l a))
-- (DFM a t) maintains the (BlockId -> a) map
-- ToDo: overlap with bc_last_in??
{-
\paragraph{Passes for forward dataflow problems}
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment | __label__pos | 0.633768 |
Error 523 Origin is unreachable due to Cloudflare Docker/oznu redirect
I have set up two servers for the same domain, using domain.com at Server1 and m.domain.com at Server2.
Server1 is running on Docker-Oznu/docker image for cloudfare API and Nginx Proxy Manager.
Server2 is on Apache2, plain and simple.
All certificates have been issued and are valid.
I installed certbot and generated an SSL certificate successfully, created an A record on Cloudflare for m.domain.com > Server2 IP.
On server1, Cloudflare API is automatically changing the Server2 IP to Server1 IP, so even Nginx pointing m.domain.com to server2 IP, the page returns error 523 Origin is unreachable.
Here are the log registries for server1 Cloudflare API:
crond: USER root pid 296 cmd /etc/cont-init.d/50-ddns
No DNS update required for m.domain.com (yyy.www.www.x).
On Nginx Proxy Manager I set m.domain.com pointing to server2 IP: 129.213.www.37 and used a valid ssl cert.
domain.com is loading with no problems.
Can you point me to an article or suggest a configuration for the API? I thought I would get off Docker and use plain old Apache on server1 as well, but you only have Certbot dns-Cloudflare request for new certificates, I have never seen a method for subdomain creation on the API out of docker, could you point me to the place in the documentation for this or let me know what to do please?
I solved it by adding the info: -e DNS_SERVER=10.0.0.2
To oznu new stack:
version: '2'
services:
cloudflare-ddns:
image: oznu/cloudflare-ddns:latest
restart: always
environment:
- API_KEY=my token
- ZONE=domain.app
- SUBDOMAIN=m
- e DNS_SERVER=vvvv
- PROXIED=true
- e CRON=*/5 * * * *
1 Like | __label__pos | 0.581999 |
Documentation
Filehandler function
This function is used to handle file processing like watching file in a folder, copy and paste a particular extension file, delete a file and verify text from the file.
Select SET command from the Action drop-down, leave the Screen name blank, write a variable name in the Element key, click on form, you will see form will open, select function from the drop down then select FILEHANDLER function and select key value from cmd field. The file handler function shown below:
Select “watch” as a key value in cmd field.
After completing this step, the test step will look as below:
This function perform four actions as given below:
• Watch
• Copy
• Delete
• Verifytext
Watch:
Watch is used to find out the exact path of a file by looking into a folder using file extension.
Syntax: ${__filehandle(cmd=action name,folder=folder path,extension=extension type,prefix=file name prefix, timeout=time taken to search the file)}
where, cmd denotes the command user wants to perform like the watch. folder denotes which folder is to be watched extension is the file extension to watch in a particular folder example txt, xls, pdf, etc. prefix is the filename prefix if the user wants to give timeout denotes time taken to search the file.
Note: prefix and time out is an optional parameter and if timeout is not given explicitly then default timeout is 5 minutes.
Example: ${__filehandle(cmd=watch,folder=C:\BeatBlip\DemoTwo\sourcelocation,extension=txt)}
In the above example spath is the name of a variable which will store the complete path of the file.
Copy:
Copy is used to copy the file from source location to destination folder.
Example: ${__filehandle(cmd=copy,source=C:\BeatBlip\Demo1\file1.txt,destination=C:\BeatBlip\Demo2)}
In the above snapshot, output variable will be set with true if file is copied successfully.
Delete:
Delete is used to delete a particular file.
Example: ${__filehandle(cmd=delete,file= C:\BeatBlip\Demo1\file1.txt )}
For verifytext:
verifytext is used to verify if the given text is present in the file or not.
Example: ${__filehandle(cmd=verifytext,file= C:\BeatBlip\Demo1\file1.txt ,text=Hello)}
Was this page helpful? | __label__pos | 0.991329 |
blob: f709c784bf1296e21de0a33175e403e86a974df6 [file] [log] [blame]
/*
* Copyright (C) 2002 Jeff Dike ([email protected])
* Licensed under the GPL
*/
#ifndef __UM_MMU_CONTEXT_H
#define __UM_MMU_CONTEXT_H
#include "linux/sched.h"
#include "choose-mode.h"
#include "um_mmu.h"
#define get_mmu_context(task) do ; while(0)
#define activate_context(tsk) do ; while(0)
#define deactivate_mm(tsk,mm) do { } while (0)
extern void force_flush_all(void);
static inline void activate_mm(struct mm_struct *old, struct mm_struct *new)
{
/*
* This is called by fs/exec.c and fs/aio.c. In the first case, for an
* exec, we don't need to do anything as we're called from userspace
* and thus going to use a new host PID. In the second, we're called
* from a kernel thread, and thus need to go doing the mmap's on the
* host. Since they're very expensive, we want to avoid that as far as
* possible.
*/
if (old != new && (current->flags & PF_BORROWED_MM))
CHOOSE_MODE(force_flush_all(),
switch_mm_skas(&new->context.skas.id));
}
static inline void switch_mm(struct mm_struct *prev, struct mm_struct *next,
struct task_struct *tsk)
{
unsigned cpu = smp_processor_id();
if(prev != next){
cpu_clear(cpu, prev->cpu_vm_mask);
cpu_set(cpu, next->cpu_vm_mask);
if(next != &init_mm)
CHOOSE_MODE((void) 0,
switch_mm_skas(&next->context.skas.id));
}
}
static inline void enter_lazy_tlb(struct mm_struct *mm,
struct task_struct *tsk)
{
}
extern int init_new_context_skas(struct task_struct *task,
struct mm_struct *mm);
static inline int init_new_context_tt(struct task_struct *task,
struct mm_struct *mm)
{
return(0);
}
static inline int init_new_context(struct task_struct *task,
struct mm_struct *mm)
{
return(CHOOSE_MODE_PROC(init_new_context_tt, init_new_context_skas,
task, mm));
}
extern void destroy_context_skas(struct mm_struct *mm);
static inline void destroy_context(struct mm_struct *mm)
{
CHOOSE_MODE((void) 0, destroy_context_skas(mm));
}
#endif
/*
* Overrides for Emacs so that we follow Linus's tabbing style.
* Emacs will notice this stuff at the end of the file and automatically
* adjust the settings for this buffer only. This must remain at the end
* of the file.
* ---------------------------------------------------------------------------
* Local variables:
* c-file-style: "linux"
* End:
*/ | __label__pos | 0.999207 |
How to Calculate Percent Agreement Between Two Numbers
••• Nick Dolding/Stone/GettyImages
The calculation of the percent agreement requires you to find the percentage of difference between two numbers. This value can prove useful when you want to see the difference between two numbers in percentage form. Scientists may use the percent agreement between two numbers to show the percentage of relationship between varied results. Calculating the percent difference requires you to take the difference of values, divide it by the average of the two values and then multiply that number times 100.
Subtract the two numbers from each other and place the value of the difference in the position of the numerator.
For example, if you want to calculate the percent of agreement between the numbers five and three, take five minus three to get the value of two for the numerator.
Add the same two numbers together, and then divide that sum by two. Place the value of the quotient in the denominator position in your equation.
For example, using the numbers five and three again, add these two numbers together to get a sum of eight. Then, divide that number by two to get a value of four for the denominator.
Divide the numerator and denominator to get a quotient in the form of a decimal.
For example, divide the numerator's value of two by the denominator's value of four to get the decimal 0.5.
Multiply the quotient's value by 100 to get the percent agreement for the equation. You can also move the decimal place to the right two places, which provides the same value as multiplying by 100.
For example, multiply 0.5 by 100 to get a total percent agreement of 50 percent.
Tips
• The term sum refers to the value received when adding two values. Difference refers to the value received from subtraction. Quotient refers to the value received when you divide two numbers.
Related Articles
How to Calculate Percent Difference With Three Sums
How to Calculate the Percentage of Another Number
How do I Calculate 0.1%?
How to Find the X Intercept of a Function
How to Find a Percent of a Fraction
How to Increase a Number by a Percentage
How to Figure a Percentage of a Whole Number
How to Calculate the Midpoint Between Two Numbers
How to Calculate Two Thirds of a Number
How to Calculate Isotopes
How to Calculate a Sigma Value
How to Calculate Percent Abundances
How to Calculate a 10 Percent Discount
How to Calculate Percent Relative Range
How to Find the Answer to 20% of What Number Is 8?
How to Change 1/4 to a Decimal Form
How to Change Any Number to a Percent, With Examples
How to Convert From Moles Per Liter to Percentage
Dont Go!
We Have More Great Sciencing Articles! | __label__pos | 0.702556 |
如何解决Elasticsearch的深度翻页问题
0.505字数 667阅读 801
使用ES做搜索引擎拉取数据的时候,如果数据量太大,通过传统的from + size的方式并不能获取所有的数据(默认最大记录数10000),因为随着页数的增加,会消耗大量的内存,导致ES集群不稳定。
ES提供了3中解决深度翻页的操作,分别是scroll、sliced scroll 和 search after:
scroll
scroll api提供了一个全局深度翻页的操作, 首次请求会返回一个scroll_id,使用该scroll_id可以顺序获取下一批次的数据;scroll 请求不能用来做用户端的实时请求,只能用来做线下大量数据的翻页处理,例如数据的导出、迁移和_reindex操作,还有同一个scroll_id无法并行处理数据,所以处理完全部的数据执行时间会稍长一些。
• 例如我们使用scroll翻页获取包含elasticsearch的Twitter,那么首次请求的语句如下:
POST /twitter/_search?scroll=1m
{
"size": 100,
"query": {
"match" : {
"title" : "elasticsearch"
}
}
}
其中scroll=1m是指scroll_id保留上下文的时间
• 首次请求会返回一个scroll_id,我们根据这个值去不断拉取下一页直至没有结果返回:
POST /_search/scroll
{
"scroll" : "1m",
"scroll_id" : "DXF1ZXJ5QW5kRmV0Y2gBAAAAAAAAAD4WYm9laVYtZndUQlNsdDcwakFMNjU1QQ=="
}
针对scroll api下,同一个scroll_id无法并行处理数据的问题,es又推出了sliced scroll,与scroll api的区别是sliced scroll可以通过切片的方式指定多scroll并行处理。
sliced scroll
sliced scroll api 除指定上下文保留时间外,还需要指定最大切片和当前切片,最大切片数据一般和shard数一致或者小于shard数,每个切片的scroll操作和scroll api的操作是一致的:
GET /twitter/_search?scroll=1m
{
"slice": {
"id": 0,
"max": 2
},
"query": {
"match" : {
"title" : "elasticsearch"
}
}
}
GET /twitter/_search?scroll=1m
{
"slice": {
"id": 1,
"max": 2
},
"query": {
"match" : {
"title" : "elasticsearch"
}
}
}
因为支持并行处理,执行时间要比scroll快很多。
search after
上面两种翻页的方式都无法支撑用户在线高并发操作,search_after提供了一种动态指针的方案,即基于上一页排序值检索下一页实现动态分页:
• 首次查询
GET twitter/_search
{
"size": 10,
"query": {
"match" : {
"title" : "elasticsearch"
}
},
"sort": [
{"date": "asc"},
{"tie_breaker_id": "asc"}
]
}
因为是动态指针,所以不需要像scroll api那样指定上下文保留时间了
• 通过上一页返回的date + tie_breaker_id最后一个值做为这一页的search_after:
GET twitter/_search
{
"size": 10,
"query": {
"match" : {
"title" : "elasticsearch"
}
},
"search_after": [1463538857, "654323"],
"sort": [
{"_score": "desc"},
{"tie_breaker_id": "asc"}
]
}
说白了 search_after 并没有解决随机跳页查询的场景,但是可以支撑多query并发请求;search_after 操作需要指定一个支持排序且值唯一的字段用来做下一页拉取的指针,这种翻页方式也可以通过bool查询的range filter实现。 | __label__pos | 0.998745 |
关于二叉树的算法题
关于二叉树的算法题,用java写,包括剑指offer和网上各种。
二叉树的下一个节点
给定一个二叉树和其中的一个结点,请找出中序遍历顺序的下一个结点并且返回。注意,树中的结点不仅包含左右子结点,同时包含指向父结点的指针。
/*
public class TreeLinkNode {
int val;
TreeLinkNode left = null;
TreeLinkNode right = null;
TreeLinkNode next = null;
TreeLinkNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public TreeLinkNode GetNext(TreeLinkNode pNode)
{
TreeLinkNode curNode = null;
// 右孩子存在
if(pNode.right!=null){
curNode = pNode.right;
while(curNode.left!=null)curNode=curNode.left;
return curNode;
}
//右孩子不存在 p是左孩子 找父节点
if(pNode.next==null)return null;
if(pNode==pNode.next.left){
return pNode.next;
}
//右孩子不存在 p是右孩子 追溯父节点 找是左孩子的那个的父节点
curNode=pNode.next;
while(curNode.next!=null){
if(curNode==curNode.next.left)
return curNode.next;
curNode=curNode.next;
}
return null;
}
}
对称的二叉树
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
boolean isSymmetrical(TreeNode pRoot)
{
return isSymmetrical(pRoot, pRoot);
}
boolean isSymmetrical(TreeNode pRoot1,TreeNode pRoot2)
{
if(pRoot1==null&&pRoot2==null)return true;
else if(pRoot1==null||pRoot2==null)return false;
else if(pRoot1.val!=pRoot2.val)return false;
return isSymmetrical(pRoot1.left,pRoot2.right)&&isSymmetrical(pRoot2.left,pRoot1.right);
}
}
按之字形顺序打印二叉树
请实现一个函数按照之字形打印二叉树,即第一行按照从左到右的顺序打印,第二层按照从右至左的顺序打印,第三行按照从左到右的顺序打印,其他行以此类推。
注意: 偶数行reverse方法效率太低了。
import java.util.ArrayList;
import java.util.Stack;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
int layer =1;
Stack<TreeNode> s1 = new Stack<TreeNode>(); //存奇数层
s1.push(pRoot);
Stack<TreeNode> s2 = new Stack<TreeNode>();//存偶数层
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
while(!s1.empty()||!s2.empty()){
if(layer%2!=0){
ArrayList<Integer> temp = new ArrayList<Integer>();
while(!s1.empty()){
TreeNode node = s1.pop();
if(node!=null){
temp.add(node.val);
System.out.print(node.val+' ');
s2.push(node.left);
s2.push(node.right);
}
}
if(!temp.isEmpty()){
list.add(temp);
layer++;
System.out.println();
}
}
else{
ArrayList<Integer> temp = new ArrayList<Integer>();
while(!s2.empty()){
TreeNode node = s2.pop();
if(node!=null){
temp.add(node.val);
System.out.print(node.val+' ');
s1.push(node.right);
s1.push(node.left);
}
}
if(!temp.isEmpty()){
list.add(temp);
layer++;
System.out.println();
}
}
}
return list;
}
}
把二叉树打印成多行
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
import java.util.ArrayList;
import java.util.*;
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
if(pRoot==null)return list;
Queue<TreeNode> layer = new LinkedList<TreeNode>();
ArrayList<Integer> temp = new ArrayList<Integer>();
layer.add(pRoot);
int start=0,end=1;
while(!layer.isEmpty()){
TreeNode cur = layer.remove();
temp.add(cur.val);
start++;
if(cur.left!=null)layer.add(cur.left);
if(cur.right!=null)layer.add(cur.right);
if(start==end){
end=layer.size();
start=0;
list.add(temp);
temp=new ArrayList<Integer>();
}
}
return list;
}
}
序列化二叉树
请实现两个函数,分别用来序列化和反序列化二叉树
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
String Serialize(TreeNode root) {
if(root==null)return "";
StringBuilder res = new StringBuilder();
Serialize2(root,res);
return res.toString();
}
void Serialize2(TreeNode root,StringBuilder res){
if(root==null){
res.append("#,");
return ;
}
res.append(root.val);
res.append(',');
Serialize2(root.left,res);
Serialize2(root.right,res);
}
int index=-1;
TreeNode Deserialize(String str) {
if(str.length()==0)return null;
String[] strs = str.split(",");
return Deserialize2(strs);
}
TreeNode Deserialize2(String[] strs){
index++;
if(!strs[index].equals("#")){
TreeNode root = new TreeNode(0);
root.val=Integer.parseInt(strs[index]);
root.left=Deserialize2(strs);
root.right=Deserialize2(strs);
return root;
}
return null;
}
}
二叉搜索树的第k个结点
给定一颗二叉搜索树,请找出其中的第k大的结点。例如, 5 / \ 3 7 /\ /\ 2 4 6 8 中,按结点数值大小顺序第三个结点的值为4。
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
int index=0;
TreeNode KthNode(TreeNode root, int k)
{
if(root!=null&&k>=1){
TreeNode node = KthNode(root.left,k);
if(node!=null)return node;
index++;
if(index==k)return root;
node= KthNode(root.right,k);
if(node!=null)return node;
}
return null;
}
}
Author: Ykk
Link: https://ykksmile.top/posts/17951/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally. | __label__pos | 0.994378 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.