text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
Introducing DTrace in GlassFish 3.1.1 By ByronNevins on Jul 28, 2011 This is the first in a series of blogs about Dtrace in GlassFish. I will present concrete examples in upcoming blogs. This blog is an overview of this powerful new capability. An entire book could be (and has been) written just to describe DTrace itself. There are many many useful documents on the internet about DTrace and its usage. At the end of this blog I've referenced a few good ones that I've read. DTrace is a tool available currently on Solaris 10 and Mac OS X that will dynamically instrument already-running code for the purposes of seeing what is going on inside software. This includes the OS itself. You can probe into kernel-mode in addition to user-mode. GlassFish automatically supports DTrace. For every Probe that is registered in GlassFish, a corresponding DTrace probe is generated and made available to DTrace. This includes any probes that you create yourself such as in your Applications. See [1] for a tutorial on this. In order for the DTrace probes to be available you need to do 3 things from the GlassFish end: - GlassFish must be running in JDK 7 - Dtrace must be enabled. Simply run this command: asadmin enable-monitoring --dtrace - You must have glassfish-dtrace.jar copied to the GlassFish modules directory. Update center will set things up for you by doing the following - You must use an official distribution: - Open Source Distribution - Oracle GlassFish Server Distribution - Official Oracle GlassFish Server page is located here - Run: <installdir>/bin/updatetool to bootstrap update clients. - Run: <installdir>/bin/pkg install glassfish-monitoring-dtrace@3.1.1 to install the DTrace package Of course you also have to turn on the monitoring levels for what you are interested in. To turn Monitoring up full-blast for everything run these commands (you can make one huge command out of it and stuff it into a script like I do): asadmin enable-monitoring --target server --modules deployment=HIGH asadmin enable-monitoring --target server --modules connector-connection-pool=HIGH asadmin enable-monitoring --target server --modules connector-service=HIGH asadmin enable-monitoring --target server --modules ejb-container=HIGH asadmin enable-monitoring --target server --modules http-service=HIGH asadmin enable-monitoring --target server --modules jdbc-connection-pool=HIGH asadmin enable-monitoring --target server --modules jms-service=HIGH asadmin enable-monitoring --target server --modules jvm=HIGH asadmin enable-monitoring --target server --modules orb=HIGH asadmin enable-monitoring --target server --modules thread-pool=HIGH asadmin enable-monitoring --target server --modules transaction-service=HIGH asadmin enable-monitoring --target server --modules web-container=HIGH asadmin enable-monitoring --target server --modules jersey=HIGH asadmin enable-monitoring --target server --modules jpa=HIGH asadmin enable-monitoring --target server --modules security=HIGH asadmin enable-monitoring --target server --modules web-services-container=HIGH Obviously you have to be on an OS that has dtrace! You can quickly and easily see that everything is registered correctly and available for running in DTrace scripts with this command: dtrace -l | grep glassfish This will show 151 or so built-in GlassFish probes. Here is one line of the output: 39462 glassfish20383 web web-module webModuleStartedEvent 20383 is the Process ID of the GlassFish Server. Whenever a web module is started the DTrace probe will be called with some arguments like the name of the web-module, etc. The beauty of DTrace is that the DTrace probe inside of GlassFish is a no-op unless a DTrace script happens to be running. In that case and in only that case the DTrace probe code gets dynamically instrumented to call into the OS's DTrace framework. When the script ends, the probe gets un-instrumented. There is almost no overhead unless a DTrace script is running. There are limitless applications for this technology. You can create on-the-fly scripts that attach to an already-running GlassFish server. Everything can be enabled dynamically - the server never needs to be restarted for the magic to happen. DTrace is so powerful it has its own programming language named "d". It is beyond the scope of this blog to do more than chip at the surface of the DTrace engine. An example might be choosing a pair of bookend probes. E.g. a start-transaction/end-transaction pair. Or a HTTP service startRequest/endRequest pair. You can easily have a DTrace script measure the time between the 2 calls and print out this information. Since it is a programming language you can even save them into variables and crunch the data at the end of the script. Another example might be that you want to see every file that is opened - but only between a bookend pair (i.e. you are filtering the deluge of file openings to those that happen to occur during the time-slice of your bookend). Create or download the app from [1]. Now add something more interesting to the webapp like, for instance, a form. Now call a probe everytime the form is processed. Pass a String the user enters in the form to the Probe. That String will be available in real-time to a DTrace script! This is a lot easier than it sounds. I deployed the app (MonApp) from the blog[1] and then ran a super-simple DTrace script. What the App does is call the probe method each time you refresh it. wget is an easy way to do the refresh. It increments a counter and calls the probe with a string like so: "Hello #XX". I didn't even bother writing a script file - I just ran it from a command line: dtrace -n 'fooblog*::: { printf("PID:%d APP:%s %s", pid, execname, copyinstr(arg0)); }' dtrace: description 'fooblog*::: ' matched 1 probe CPU ID FUNCTION:NAME 0 39554 ProbeServlet:myProbe PID:20383 APP:java Hello #22 0 39554 ProbeServlet:myProbe PID:20383 APP:java Hello #23 0 39554 ProbeServlet:myProbe PID:20383 APP:java Hello #24 0 39554 ProbeServlet:myProbe PID:20383 APP:java Hello #25 0 39554 ProbeServlet:myProbe PID:20383 APP:java Hello #26 0 39554 ProbeServlet:myProbe PID:20383 APP:java Hello #27 I got one output line every time I refreshed MonApp in a browser. This is incredibly powerful! A string was sent from the user in a browser to a Java WebApp which then sent it off to a native program, DTrace, that was looking for it with a sophisticated scripting language. All of this can be done without ever restarting the GlassFish Server. There are truly endless possibilities. And once you kill the script -- all the instrumentation code is removed. In case you are wondering about fooblog*::: -- fooblog is the main name I gave it. The * is needed because the Monitoring Framework automatically appends the PID of the server (very handy if you are DTracing with multiple GlassFish servers simultaneously). The ::: means match ANY probe that has the main name that starts with fooblog. Whew. Hard to explain in English, easy to explain with one command: ~/gf_other/value-add/monitoring/dtrace/dtrace-samples/dtrace-scripts>dtrace -l | grep fooblog 39554 fooblog20383 samples ProbeServlet myProbe To be completely specific in the earlier command would be: dtrace -n 'fooblog20383:samples:ProbeServlet:myProbe { ..... } Dtrace uses the quadruple of names to make the namespace less unwieldy and easier to filter. References [1] My blog about adding Monitoring probes to a WebApp - DTrace Cheatsheet - Mac OS X Tutorial on DTrace - Handy One-Liners - Official GlassFish Documentation on DTrace - Java Doc
https://blogs.oracle.com/foo/entry/introducing_dtrace_in_glassfish_3
CC-MAIN-2015-32
refinedweb
1,253
52.9
I am trying to make a program that 1) Ask how many positions the user would like 2) Prompt a list of address book questions for them to fill in the data 3) ask which position to view 4) show all of the information in that position Basically I am thinking of making an array. They input how many elements to make in it. it then asks a list of questions I made in a structure and then asks which element to view and when they pick an element it shows the entire thing. This is what I have so far: As you can see for now I am just working with the first two entries in the structure to see if I can get it to work.As you can see for now I am just working with the first two entries in the structure to see if I can get it to work.Code:#include <cstdlib> #include <iostream> using namespace std; int main(int argc, char *argv[]) { int entries; cout<<"How many entries would you like? "; cin>>entries; struct person { string phoneNumber; string wholeName; /* string address; string DOB; string eMail; string favoriteShow; string city; string state; string zip; string myspace; string favoriteFood; string gamerTag; string hairColor; string organDonar; string salary; string employer; string placeOfBirth; string mothersMaiden; string teacher; */ }; int i; for (i=0; i<entries; i++) { int myArray[entries]; person info; cout<<"Enter Phone Number: "; cin>>info.phoneNumber; cout<<endl; cout<<"Enter Whole Name: "; cin>>info.wholeName; cout<<endl; } system("PAUSE"); return EXIT_SUCCESS; } I think I am on the right track but struct myArray[entries]; gives me an error and only works when it is int myArray[entries]; but shouldn't it be struct since I am putting a structure into the array and not an integer? Please help! I would love for someone to just do the entire thing for me so I can learn from it and don't have to beat my head against the wall anymore, but any help is appreciated. =]
http://cboard.cprogramming.com/cplusplus-programming/119587-making-address-book-cplusplus-arrays-inside-structures.html
CC-MAIN-2014-42
refinedweb
337
64.88
This is one of those tasks I need to repeat every now and then and always forget the exact steps. So in the interest of sharing, I’ve written this post to demonstrate how to get started building a very simple module and cmdlet with C# and Visual Studio. A SCREENCAST IS AVAILABLE If you’d rather watch, this screencast will show you the steps I followed STEP-BY-STEP INSTRUCTIONS Create a new Visual Studio Class Library Project project. In this case, I named the library “DemoPS”. Now, we will add two references. The first to System.Management and the second to System.Management.Automation System.Management is found under the .NET tab System.Management.Automation is found under c:\program files\reference assemblies\microsoft\WindowsPowershell\v1.0 And now the references are available in Solution Explorer If you are using Visual Studio 2010 the assembly will be built using .NET 4.0, but you’ll need to switch it to use the older framework so that Powershell can load the assembly. Edit the properties of the DemoPS project and set the Target Framework to “.NET Framework 3.5” Now let’s the examine the code … Build the cmdlet and launch Powershell 2.0 Import the module with Import-Module The Get-Modules cmdlet will show you that the module is loaded and it has a single cmdlet inside it called “Get-DemoNames” the “-?” parameter is already provided for the cmdlet Now try the cmdlet … And, of course, it behaves just like any other cmdlet. So you can do things like pipe its output … Awesome article. I have tried it on windows 8.1 with VS 2012. Result is awesome. 🙂 Great way to get going. It's an awesome icebreaker. Helped me. Thanks! Helped me. Thanks Don't display code as an image please. This was very helpful, thank you. I did need to install the Windows PowerShell 2.0 SDK to get the proper Systems.Management.Automation reference. Found at:…/confirmation.aspx for anyone else who wants to just copy > paste: using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace some.namespace { [System.Management.Automation.Cmdlet(System.Management.Automation.VerbsCommon.Get,"DemoNames")] public class Get_DemoNames: System.Management.Automation.PSCmdlet { [System.Management.Automation.Parameter(Position = 0, Mandatory = false)] public string prefix; protected override void ProcessRecord() { var names = new string[] {"Chris","Charlie","Isaac","Simon"}; if (string.IsNullOrEmpty(this.prefix)) { this.WriteObject(names, true); } else { var prefixed_names = names.Select(n => this.prefix + n); this.WriteObject(prefixed_names, true); } } } } What would be nice would be a follow-up article which explains how to deploy this, say, under that C:WindowsSystem32WindowsPowershellv1.0Modules subdirectory structure. You'd then think that it would have the following: ..ModulesNameOfModuleen-USsomething.xml ..ModulesNameOfModuleNameOfModule.psd1 …and then in theory, you wouldn't need to implicitly import the module since it would be available when you fire up PowerShell.
https://blogs.msdn.microsoft.com/saveenr/2010/03/08/how-to-create-a-powershell-2-0-module-and-cmdlet-with-visual-studio-2010-screencast-included/
CC-MAIN-2018-30
refinedweb
482
52.36
Subject: Re: [boost] Closed for major changes; release freeze approaching From: Daniel James (daniel_james_at_[hidden]) Date: 2010-01-09 09:26:51 2010/1/6 John Maddock <john_at_[hidden]>: > > Looks like gcc on Darwin is producing warnings from cstdint.hpp that regular > gcc on Linux doesn't - I thought I had all those warnings quashed as well > :-( > > Any Darwin developers got any ideas? I think it's a bug in the gcc 4.0 library, not a darwin bug (it doesn't happen in darwin 4.2). This is what happens: #include <vector> // In cstdint.hpp: #define __STDC_CONSTANT_MACROS #include <stdint.h> 'vector' includes 'stdint.h' before __STDC_CONSTANT_MACROS is defined, so the macro has no effect and the integer constant macros (INT8_C etc) aren't defined. So boost's version is used which causes the warning. The easy workaround is to define the system header pragma immediately before the warning is generated (patch attached). Technically, there's an ODR violation since INT8_C can be defined differently in different units, but I don't think that's a real problem. Daniel Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2010/01/160703.php
CC-MAIN-2019-26
refinedweb
201
59.8
Hello,I'm using the services cache on Sql database. Is it possible to use a different schema than dbo for CacheEntry table? Thanks to all. As long as there is an existing CacheEntry table with a minimum of these properties it should work: CacheEntry public class CacheEntry { public string Id { get; set; } [StringLength(StringLengthAttribute.MaxText)] public string Data { get; set; } public DateTime? ExpiryDate { get; set; } public DateTime CreatedDate { get; set; } public DateTime ModifiedDate { get; set; } } Otherwise you'll need to take a copy of OrmLiteCacheClient and modify it to suit your needs. I tryed I tried to create a copy of CacheEntry table with different schema but doesn't work. Is there other solutions? Otherwise I have to rewrite the OrmLiteCacheClient class and put the right attributes in the top of CacheEntry class. Can you be more specific on what doesn't work and what exceptions you're getting? I'm assuming you're using a SuperSet of the CacheEntry table right? i.e. contains all existing fields but just adds new ones? If so what's the POCO Schema of the table you want to use instead? and what's the reason you want to use a different table? The CacheEntry table should ideally be a transparent impl detail encapsulated within OrmLiteCacheClient.
https://forums.servicestack.net/t/ormlitecacheclient-sql-table-schema/2500
CC-MAIN-2018-51
refinedweb
214
66.33
SYNOPSIS . let- ter 'b' may be specified as the second character in mode. This pro- vides . Alterna- tively, the caller can explicitly set buf as the stdio stream buffer, at the same time informing stdio of the buffer's size, using set- buffer. RETURN VALUE.() call fails, returning -1. EXAMPLE <string.h> #include <stdio.h> #include <stdlib.h> #define handle_error(msg) \ exit(EXIT_FAILURE); }\n", (long) size, ptr); free(ptr); exit(EXIT_SUCCESS); } SEE ALSO fopen(3), fopencookie(3), feature_test_macros(7) COLOPHON This page is part of release 3.23 of the Linux man-pages project. A description of the project, and information about reporting bugs, can be found at.
http://www.linux-directory.com/man3/open_wmemstream.shtml
crawl-003
refinedweb
108
60.72
28 March 2010 18:16 [Source: ICIS news] SAN ANTONIO, Texas (ICIS news)--US polyethylene exports will likely drop in the coming months, but the US could regain an edge in the export market if ethylene prices return to levels from early 2010, a plastics trader said on Sunday. Talk that US PE exports are poised for a major drop in the second quarter is widespread, as a recent surge in monomer prices have made US resin less competitive in Asia and ?xml:namespace> US ethylene prices skyrocketed in the first quarter of 2010, lifted by tight supply caused mainly by a spree of unplanned shutdowns after the turn of the year. US spot ethylene for March/April was assessed at 61.00-63.00 cents/lb ($1,345-1,389/tonne or €1,009-1,042/tonne) on Friday, down from 70.00 cents/lb in early March, but up from 42.50-43.00 cents/lb in the first week of January, according to global chemical market intelligence service ICIS pricing. Ethylene would have to drop back to the high 40.00s cents/lb for PE to be competitive again in the export market, the trader said on the sidelines of the National Petrochemical & Refiners Association (NPRA) meeting in That could happen because the According to the source, the Major US PE producers include Dow Chemical, The NPRA
http://www.icis.com/Articles/2010/03/28/9346413/NPRA-10-PE-exports-seen-dropping-but-US-could-regain.html
CC-MAIN-2014-52
refinedweb
230
56.69
Maintaining Scope in JavaScript Event Handlers via a Closure The example below and its comments should be self-explanatory: <html> <head></head> <body> <!-- This example demonstrates how to use a JavaScript closure to ensure that an event handler can access variables passed to a create_handler() function from the scope of the code in which the handler is assigned. Ordinarily if you didn't use the closure and the variable which was passed to the function changed its value the handler would have the new value, not the value of the variable at the time it was passed to the handler. Here we only pass one argument but you could modify create_handler() to pass more variables if needed. --> <div id="keep_element">Click me! I keep my value.</div> <div id="lose_element">Click me! I lose my value.</div> <script language="javascript"> function create_handler(arg){ // Return a reference to an anonymous inner function created // with a function expression:- return (function(e){ // This inner function is to be executed on the event // and when it is executed it can read, and act upon, the // parameters passed to the outer function, as well as have // access to the event. alert(arg+' Plus, we\'ve got access to the event: '+e); }); } // Get the elements we want to add the handler to var keep_elem = document.getElementById('keep_element'); var lose_elem = document.getElementById('lose_element'); // Create a variable var msg = 'The original value.'; // Add the onclick handler so that when it is called it uses the value // a at the time the handler was added. lose_elem.onclick = function(e) { alert(msg+' Plus, we\'ve got access to the event: '+e); }; keep_elem.onclick = create_handler(msg); // Set a to a different value, this won't affect the value which // is is appears in the alert box when the element is clicked. msg = 'The value has changed.'; </script> </body> </html> Frameworks such as YUI must do something similar with their automatic scope correction functionality.
https://www.jimmyg.org/blog/2008/maintaining-scope-in-javascript-event-handlers-via-a-closure.html
CC-MAIN-2020-24
refinedweb
322
62.17
Hi, We have a Windows box serving svn through mod_dav_svn and authenticating using mod_auth_sspi. It seems to be working well, except that the svn:author property ends up having the windows domain name in it which looks a little ugly. Maybe I've got things set up wrongly and someone can correct my setup, but until then I have written a hook that strips the domainname from svn:author. I say written, but its actually shamelessly stolen log-police.py that I've hacked slightly as my first attempt at python coding (so be gentle with me please). Thought I'd share it in case others are interested, Rob #!/usr/bin/python # author-police.py: Ensure that log messages end with a single newline. # See usage() function for details, or just run with no arguments. import os import sys import getopt import string import svn import svn.fs import svn.repos import svn.core # Pretend we have true booleans on older python versions try: True except: True = 1 False = 0 def fix_author(author): """Strips the domain information from the beginning of an author.""" index = author.find("\\") author = author[index+1:] return author def fix_txn(fs, txn_name): "Fix up the log message for txn TXN_NAME in FS. See fix_log_author()." txn = svn.fs.svn_fs_open_txn(fs, txn_name) old_author = svn.fs.svn_fs_txn_prop(txn, "svn:author") if old_author is not None: new_author = fix_author(old_author) if new_author != old_author: svn.fs.svn_fs_change_txn_prop(txn, "svn:author", new_author) def fix_rev(fs, revnum): "Fix up the log message for revision REVNUM in FS. See fix_log_author()." old_author = svn.fs.svn_fs_revision_prop(fs, revnum, 'svn:author') if old_author is not None: new_author = fix_author(old_author) if new_author != old_author: svn.fs.svn_fs_change_rev_prop(fs, revnum, "svn:author", new_author) def usage_and_exit(error_msg=None): """Write usage information and exit. If ERROR_MSG is provide, that error message is printed first (to stderr), the usage info goes to stderr, and the script exits with a non-zero status. Otherwise, usage info goes to stdout and the script exits with a zero status.""" import os.path stream = error_msg and sys.stderr or sys.stdout if error_msg: stream.write("ERROR: %s\n\n" % error_msg) stream.write("USAGE: %s [-t TXN_NAME | -r REV_NUM | --all-revs] REPOS\n" % (os.path.basename(sys.argv[0]))) stream.write(""" Ensure that log messages end with exactly one newline and no other whitespace characters. Use as a pre-commit hook by passing '-t TXN_NAME'; fix up a single revision by passing '-r REV_NUM'; fix up all revisions by passing '--all-revs'. (When used as a pre-commit hook, may modify the svn:log property on the txn.) """) sys.exit(error_msg and 1 or 0) def main(ignored_pool, argv): repos_path = None txn_name = None rev_name = None all_revs = False try: opts, args = getopt.getopt(argv[1:], 't:r:h?', ["help", "all-revs"]) except: usage_and_exit("problem processing arguments / options.") for opt, value in opts: if opt == '--help' or opt == '-h' or opt == '-?': usage_and_exit() elif opt == '-t': txn_name = value elif opt == '-r': rev_name = value elif opt == '--all-revs': all_revs = True else: usage_and_exit("unknown option '%s'." % opt) if txn_name is not None and rev_name is not None: usage_and_exit("cannot pass both -t and -r.") if txn_name is not None and all_revs: usage_and_exit("cannot pass --all-revs with -t.") if rev_name is not None and all_revs: usage_and_exit("cannot pass --all-revs with -r.") if rev_name is None and txn_name is None and not all_revs: usage_and_exit("must provide exactly one of -r, -t, or --all-revs.") if len(args) != 1: usage_and_exit("only one argument allowed (the repository).") # svn_path_canonicalize doesn't seem to work from a stock 1.3.0 on windows # repos_path = svn.core.svn_path_canonicalize(args[0]) repos_path = args[0] # A non-bindings version of this could be implemented by calling out # to 'svnlook getlog' and 'svnadmin setlog'. However, using the # bindings results in much simpler code. fs = svn.repos.svn_repos_fs(svn.repos.svn_repos_open(repos_path)) if txn_name is not None: fix_txn(fs, txn_name) elif rev_name is not None: fix_rev(fs, int(rev_name)) elif all_revs: # Do it such that if we're running on a live repository, we'll # catch up even with commits that came in after we started. last_youngest = 0 while True: youngest = svn.fs.svn_fs_youngest_rev(fs) if youngest >= last_youngest: for this_rev in range(last_youngest, youngest + 1): fix_rev(fs, this_rev) last_youngest = youngest + 1 else: break if __name__ == '__main__': sys.exit(svn.core.run_app(main, sys.argv)) --------------------------------------------------------------------- To unsubscribe, e-mail: dev-unsubscribe@subversion.tigris.org For additional commands, e-mail: dev-help@subversion.tigris.org Received on Thu Mar 16 16:06:42 2006 This is an archived mail posted to the Subversion Dev mailing list.
https://svn.haxx.se/dev/archive-2006-03/0775.shtml
CC-MAIN-2019-04
refinedweb
761
57.87
Introduction: Dummy Security Camera With Spark.io Security Cameras can get very expensive. I took an old bullet camera housing, added a spark.io Core with a Sparkbutton and a PIR (Passive infrared) sensor to make it respond to detected motion. When the PIR alerts, the LED ring on the Sparkbutton starts pulsing red. In standby mode, a slow chasing algorithm loops blue. Lets build it! Step 1: BOM 1 Spark Button 1 battery pack (or other power source for the USB cable) 1 camera housing and mounting bracket 3 M/F jumper wires Step 2: Binding the Spark Core It's a bit of trick getting your Core up and running. You need to be sure you have a solid wifi connection when you try to bind it to your account. Here's a summary of the steps. - Create a free account at - Install the app on your android or iphone - Bind the Core to your account using the app. You'll need the SSID and passcode for your hotspot. Once you have the heartbeat LED signal, you're good to go. A more detailed installation guide and troubleshooting help are at. Step 3: Wire Up the Circuit Connect the power, ground and signal leads to the PIR sensor - Red - Vcc to 3V3 filtered - Black - Gnd to Ground - Blue - Out to pin D7 The PIR outputs a high (3V) signal until it detects motion. Upon detection, it drives the digital input low triggering the sketch to execute alert mode. Step 4: Load the Sketch You can find the latest revision of the code here. /*<br>Created to read either button 2 or a PIR sensor to trigger an alert mode on the SparkButton. Copyright 2015, Bill Shaw. This work is licensed under the Creative Commons Attribution-ShareAlike 4.0 International License. To view a copy of this license, visit <a href="." rel="nofollow">.</a> Rev 0.1 01/05/2015 BS Initial release */ #include "SparkButton/SparkButton.h" #include "math.h" SparkButton b = SparkButton(); int ledPos = 0; int PIR = D7; void setup() { // Tell b to get everything ready to go b.begin(); pinMode(PIR, INPUT); } void loop(){ if (b.buttonOn(2) || !digitalRead(PIR)) { //alert mode on button press or PIR activation // for(int i=1; i<13; i++) { // b.ledOn(i, 127,0,0); // delay(10); b.allLedsOn(127,0,0); // } // for(int i=1; i<13; i++) { // b.ledOff(i); // delay(10); // } delay(80); b.allLedsOff(); delay(80); } else { //standby mode ledPos += 1; ledPos %= 12; //modulo b.ledOn(ledPos, 0, 20, 20); // Now turn that LED on // Wait a mo' delay(160); // Turn the LEDs off b.ledOff(ledPos); } } Step 5: Build It! You'll need to mount the PIR in front of the SparkButton so it is facing through the glass in the front of the camera enclosure. Double sided foam tape works well. Mount this assembly inside of the enclosure and power it up. I 3D printed a mount for the PIR sensor and to keep the entire assembly flush on the glass. You can download the STL files your self from... It will take the PIR sensor about 10 seconds to stabilize. Once it does, you should get a slow, chasing cyan light around the PIR. When the PIR detects motion, you'll see the ring start flashing all LEDs rapidly in red. I powered the entire setup using the 6W Voltaic battery and solar panel. Seal the enclosure and mount it somewhere where observers can clearly know they're being watched. Recommendations We have a be nice policy. Please be positive and constructive. This is a neat dummy camera, I like it. Smart idea!
http://www.instructables.com/id/Dummy-Security-Camera-with-Sparkio/
CC-MAIN-2018-17
refinedweb
609
76.32
I am trying to pass two different arrays to subroutine in same file. First array @act_table is two dimentional array and another is simple array (@colm) for ($h=1; $h<=$arg[1]; $h++) { my @colm; for ($t=1;$t<=$arg[2];$t++) { push @colm, $act_table[$t][$h]; } Column(@act_table,@colm); } for ($i=1; $i<=$arg[2]; $i++) { for ($n=1;$n<=$arg[1];$n++) { #print" $table_arr[$i][$n]"; } } sub Column { no warnings; my @actcol=@_; my @col=@_; $colno++; print "In column : $colno\n"; foreach $_ (@col) { print "$_\n "; $_=~s/(<Tc(?:\s?\;?\s?\;?\d?)?>)(.*)/Entity_convert($2)/eg; $_= ThinSpace($_); #print "***************** $_\n"; } } [download] When i print @col trough foreach loop i get garbage values first and then actual values This is really urgent. Can anybody please tell me what going wrong in my code? Column(\@act_table, \@colm); sub Column { my ($actcol, $col) = @_; # now iterate over @$col instead of @col } [download] Column(\@act_table,\@colm); ... sub Column { no warnings; my $actcol = shift; my $col = = shift; $colno++; print "In column : $colno\n"; foreach (@$col) { print "$_\n "; $_=~s/(<Tc(?:\s?\;?\s?\;?\d?)?>)(.*)/Entity_convert($2)/eg; $_= ThinSpace($_); #print "***************** $_\n"; } } [download] Thak you so much for your help However when i am passing arrays like this, It is adding one extra $_ in my array for ($h=0; $h<=$arg[1]-1; $h++) { my @colm=""; for ($t=0;$t<=$arg[2]-1;$t++) { push @colm, $act_table[$t][$h]; print "***##$act_table[$t][$h]\n"; } Column(\@act_table,\@colm); } } Alnfirstcol (@firstcol); ## Sends first column for alignment to Subro +utine Alnfirstcol #foreach my $item (@firstcol) { #print "$item \n"; #} ## Subroutine : Entity_conv ## Sends cellwise data to Entity module to convert entities ## After entity conversion sends cellwise data ThinSpace subroutine to + add thin space wherever required ## Sends column to Text_Nontext subroutine to evaluate whether column +is contains text data or non text data sub Column { no warnings; my $actcol=shift; my $col=shift; $colno++; foreach (@$col) { print "$_\n"; $_=~s/(<(?:Tr|Tc)(?:\s?\;?\s?\;?\d?)?>)(.*)/$1.Entity_convert( +$2)/eg; } foreach (@$col) { #print "After ## $_\n"; } ThinSpace(\@$col,\@$actcol); return (); } [download] use v6; my @a = 1, 2, 3; my @b = <a b c>; column(@a, @b); sub column(@first, @second) { say "First: @first.join(', ')"; say "Second: @second.join(', ')"; } [download] I know you're doing a lot of work on the Perl6 project and keen to raise its profile which is, I'm sure, why you posted that snippet. Sadly, I'm not sure what it will achieve. I'd grade myself somewhere between senior novice and junior intermediate and that snippet leaves me cold. Many, if not most, Perl5 coders probably have a similar feeling. "So what?", you'd be entitled to ask, and it would be a fair question. If anyone had a question about a Perl6 script would they come to the Monastery? I can't remember seeing any (but I could be wrong on that). Anyhows, it may be worth posting a meditation on the relationship between the Monastery and Perl6 to start a discussion on the subject. It is a different language isn't it? I'd be intrested to hear what other monks think. Wouldn't it be best if a Perl6er kicked it off (he says passing the buck)? Oh, and I can give you a tip for Perl6: Hurry up. :-) maybe we could use the post title to mark such posts. it might not be interesting to perl5 users, it might also not be interesting to perl 6 users, but it's definitely interesting for those who know perl5 and learn perl 6. if we mark such posts with something like "perl5 vs perl6" in the title it might become a nice collection of examples what perl5 users want to learn about perl 6. I don't want to sound jerk, but what's wrong about Mortiz's answer? How many times somebody asks something and we say "use shell script for that", "use this module instead of that other module" or "do it in C" ? Is up to the person that makes the question to pick the best answer for his/her problem - remember TIMTOWTDI. You can just ignore those answers you don't like. On the other hand P5 and P6 share *almost* the same community ( fortunately ) so its perfectly fine to me to use the same tools - in this case the perlmonks - to discuss ideas, post snippets and suggest possible solutions.. "So what?", you'd be entitled to ask, and it would be a fair question. Of course it is a fair question. And the simple answer is that I educate people about Perl. Which is what this site is all about, after all. If anyone had a question about a Perl6 script would they come to the Monastery? I can't remember seeing any (but I could be wrong on that). Having tried to answer most of them, I have noticed them. Maybe you need to take a second look, or raise your awareness. Anyhows, it may be worth posting a meditation on the relationship between the Monastery and Perl6 to start a discussion on the subject. You mean like Re: What is the scope of Perl Monks?? or maybe New PerlMonks for Perl 6 - A Good Idea? It is a different language isn't it? It's a different language than Perl 5, and still Perl. As someone who had a Perl6 question, I went to IRC and to the Monastery. moritz told me about KeySet, which will be the exact solution to my problem, once it works. In the meantime, I'm using a plain old hash. In my trivial perl6 sudoku-solver, I do pass multiple arrays into a routine. On the other hand, while the knowledge that it will be available might raise excitement for the metamorphosis of the rudimentary Perl6 into a hallucinogenic butterfly, it isn't really relevant to this week's requirements, is it? As Occam said: Entia non sunt multiplicanda praeter necessitatem. I'd grade myself somewhere between senior novice and junior intermediate and that snippet leaves me cold. Do you like using explicit references? (I didn't ask "Do you like the effect you get when you must use explicit references in Perl 5?") Me, I won't miss them. Roll on Perl 6. I really enjoy moritz's Perl 6 responses. I think they're a practical and effective way to promote the language. You might even see moritz as a modern day merlyn. :) You see, twenty years ago merlyn loved Perl 3 so much that he insisted on answering requests for Unix shell/sed/awk help with snippets of Perl code. So much so that many posters resorted to inserting "No Perl please" in their posts! As you might expect, this only provoked him further, and the barrage of Perl 3 snippet responses intensified. So Perl 6 still passes references, its just that the syntax no longer requires the \. It's slightly more accurate to say (from the language design point of view) that Perl 6 passes these values by reference. Unfortunately, then things get complex with other parameter traits and so on and so forth. To quote Apocalyse 6 Please note that the Apocalypses are mostly historical documents. S06 is what you should consider. but isn't the Perl 6 solution using references as well? Yes. Under the hood, every argument passing uses references, unless the parameter is decorated with the is copy trait. Unlike in Perl 5, these references are write protected by default. Not only the backslash, but also the dereferencing inside the subroutine. Since (nearly) everything in Perl 6 is a reference, references are transparent, and don't require special syntax on either
http://www.perlmonks.org/?node_id=862178
CC-MAIN-2015-06
refinedweb
1,285
71.24
Ajaxful Rating jQuery Provides a simple way to add rating functionality to your application. This fork uses jQuery instead of prototype and uses unobtrusive javascript. Currently, it only supports Rails 2.3.×. Repository Find it at The original repository, which uses Prototype, is located at Demo There’s a working demo project at Just migrate and run… Or view it live: Instructions Install To install the gem run the next command: gem install ajaxful_rating_jquery You can configure it in your environment.rb file also: config.gem "ajaxful_rating_jquery" Generate script/generate ajaxful_rating UserModelName The generator takes one argument: UserModelName, which is the name of your current user model. This is necessary to link both the rate and user models. Also this generator copies the necessary images, styles, etc. Example: I suppose you have generated already an authenticated model… script/generate authenticated user sessions script/generate ajaxful_rating user So this call will create a Rate model and will link it to your User model. Prepare To let a model be rateable just add ajaxful_rateable. You can pass a hash of options to customize this call: :starsMax number of stars that can be submitted. :allow_updateSet to true if you want users to be able to update their votes. :cache_columnName of the column for storing the cached rating average. :dimensionsArray of dimensions. Allows to rate the model on various specs, like for example: a car could be rated for its speed, beauty or price. class Car < ActiveRecord::Base ajaxful_rateable :stars => 10, :dimensions => [:speed, :beauty, :price] end Then you need to add a call ajaxful_rater in the user model to make your User model able to rate objects. class User < ActiveRecord::Base ajaxful_rater end Finally, as a mere recommendation to make it even easier, modify your routes to map a rate action: map.resources :cars, :member => {:rate => :post} Use it To add the star links you need to call the helper method ratings_for. It tries to call current_user method as the rater instance. You can pass :static as the second param to display only the static stars (not clickables). And also you can pass the dimension you want to show the ratings for. #show.html.erb <%= ratings_for @article %> #To display static stars: <%= ratings_for @article, :static %> #To display the ratings for a dimension: <%= ratings_for @article, :dimension => :speed %> Or you can specify a custom user instance by passing it as parameter. <%= ratings_for @article, @user %> By default ratings_for will display the average user rating. If you would like it to display the rating for the current_user, then set the :show_user_rating parameter to true. For example: # To display the rating for the current user (current_user): <%= ratings_for @article, :show_user_rating => true %> # To change the size of the stars you can also specify an optional :size value. If none is set it uses the large size, otherwise you can specify medium or small: <%= ratings_for @article, :size => "medium" %> # To display the rating for the user specified by @user: <%= ratings_for @article, @user, :show_user_rating => true %> There’s a condition here, if you didn’t add the route rate to your resource (as shown above) or you named it different, you’ll need to pass the url to the correct action in your controller: <%= ratings_for @article, :url => your_rate_path(@article) %> +h3. Important! To display the stars properly you need to add a call in the head of your layout, which will generate the required CSS style for the list. Also don’t forget to include jQ—uery. It’s also important to note that this call MUST be within your head tags in your layout, as for now it seems to doesn’t work with the content_for tag. #within the head tags of your layout... <%= javascript_include_tag "" %> <%= ajaxful_rating_style %> <%= ajaxful_rating_script %> When a user submits a rating it will call the action in your controller, for example (if you added the rate route): def rate @car = Car.find(params[:id]) @car.rate(params[:stars], current_user, params[:dimension]) average = @product.rate_average(true, params[:dimension]) width = (average / @car.class.max_stars.to_f) * 100 render :json => {:id => @car.wrapper_dom_id(params), :average => average, :width => width} end There are some more options for this helper, please see the rdoc for details. Dimensions From now on you can pass an optional parameter to the rates method for your rateable object to retrieve the corresponding rates for the dimension you want. For example, you defined these dimensions: class Car < ActiveRecord::Base ajaxful_rateable :dimensions => [:speed, :beauty, :price] end And hence you can call car.rates(:price) for the price rates or car.rates(:speed) for the speed ratings and so on. Namespaces If you use the plugin inside a namespace you’ll need to specify the rating url which should points to a controller inside a namespace. Your files should be like these: routes.rb: map.namespace :admin do |admin| admin.resources :articles, :member => {:rate => :post} end views/admin/articles/show.html.erb <%= ratings_for @article, :url => rate_admin_article_path(@article) %> Cache To cache the model’s rating average add a column named rating_average to your model table: class AddRatingAverageToArticles < ActiveRecord::Migration def self.up add_column :articles, :rating_average, :decimal, :default => 0, :precision => 6, :scale => 2 end def self.down remove_column :articles, :rating_average end end If you want to customize the name of the cache column just pass it in the options hash: class Article < ActiveRecord::Base ajaxful_rateable :cache_column => :my_cached_rating end To use caching with dimensions, make sure you have a cache column defined for each dimension you want cached. So if you want to cache the spelling dimension, you’ll need to have a column called rating_average_spelling on the articles table. If you use a custom cache column name, follow the pattern cache_column_name_dimension_name to add cache columns for dimensions. Feedback If you find bugs please open a ticket at I’ll really appreciate your feedback, please contact me at kamuigt[at]gmail[dot]com Credits The original developer of ajaxify_rating, Edgar J. Suarez The helper’s style is from komodomedia with author’s permission. If you need the psd files of the stars you can grab them here Thanks to bborn for the dimensions base implementation. License This code is released under Creative Commons Attribution-Share Alike 3.0 license.
http://www.rubydoc.info/github/kamui/ajaxful_rating_jquery/master/
CC-MAIN-2014-42
refinedweb
1,018
52.9
HEMPU18 APPEAL. TUESDAY, I I DEC. 14, 1880. the BnunEAN hi rr ATIOS. The clesrinjrs of last week again how a very satisfactory condition o! business. Tlit re was an increase in tie total ol the thirty banks reporting of 15 3 per cent, over the correspond ing week last year. Excluding New York the total wao an incrrvss of 13 6 per cent. The artivity in Wa'l street speculative operations makes tbe fig ' ure high there. On the entire listouiy five cities report a decline on the wei k, nd of these only ByMcnsp, N. x , was over 10 per cent. New Orleans de diced only 3.4 per cent, a consider bit Improvement over the previous week or two ; G .lvr atin, which showed a heavy decline last week, sent in only a partial report. Many of the increases were large Memphis, 73 0 per ceDt General business ia lately under Chiistuias inft lenceo, and the general expectation is that the aoiount o! business that will be done will be lit ahead of. the Christ nif sea tines the depression set in. The demand for moi ey at thU season, and the large disbursements (but have to be made with the turn ot the yettr, have given a sharp temporary linhlneF-s to money. The New York MraWsaid on Saturday: "Money is much tights er and lenders are scrntin'zing col lator al more elonely. Imns on c.ill were Hindu as high r.s 15 per cent to day, anil a cnnci.lerable prrpnrtlon rf the Rnck Exchango borrowing was done at 10 per cent." The IlulUtin re marks: "Opinions vary as to the prospects of the money market during the remainder of the month, as a dls position to anticipate preparations for January dividend disbursements in creaees the firmness arising from other canst : and It is uncertain 'how far this will be cflst.t by gold import tiona, 'which from presoDt prospects are likely to be important in amount." The Indicator Bays: "The latest ar riva's of gold from Europe aggregate $1,088,000, and more is to come. Gold import will kill money stringency." A week ago silver quoted 45) pence an ounce; it has.been advancing since. Oar latest quotation Is 46 pence. which makes the silver in onr dollar worth 73.415 omU. England, Ger many and Austria report a better movement in trade, but the general depression la still such as to affect our oreign commerce, although we have 1 d a fair increase this year aa com pared with hut. The English home apply of wheat proves to be lower than had been anticipated, and a good demand from thia side is looked for. Congress is in session, but although there are commercial and financial questions of 'great moment In ques tion, tbe reputation ot the present . body is not such as to lead to any amendment of commercial matters from that source, dtrlkes are lean prevalent and a more settled state of things exists, but organise . tion is proceeding at rate - that indicates trouble in the future. The New York Indicator has the following "An inquirer wishes to know our opinion ot Ohio Southern incomes. We consider them good for much higher figures, although the advanoo may not come until after the holidays, Tennessee Coal and Iron touched 115 on Saturday. L ist March it to 38, and we told our readers then to buy it for ar. That was good advice. It is . going higher." THE IIANHHIII'T HI IX. Tt. wumupl Ul'l IllllUUUUflU HgAl and again to thea'tenlion ol Oongri'sc, though nevor a.;td upon there, stdl express. a livirg tans. Groat num hers of ( nr commercial people regard its enrctmeut ns vital to their inter euta. OaThur.idar laHt the Now Yoik Board of Transportation, by resolu tion, declared tho enactment of a na tional bankrupt law to he necessary to prevent fraudulent and inequitable : preferences, and also to make credits more secure, and to moro effectually protect the commerce ol this country agninst the losses now 8us!aiued by reason of the unequal and varying 8. ate ing)lvency lawn, and of the op portunities afforded dishonest debtors to chetv and defraud thuir creJitors. Tbe resolution was as follows; "That the N. w York Board of Trade and Transportation, in recognizing aad as senting the great nocesulty tierefor, again respectfully nrgesupon Congress for its Immediate norifiiduratlon the question of enacting at its present ses sion a uniform, just and national bai.krupt la; aud this board ppect fr.lly n qaea's the co-operation of all other mnrca'itile bo'lies throughout tho United Htit'S in securing immediate action by Congress in this important direction." Tbe board further resolved that "tbe Lowell bill suonld be unacted by Congress, inas much as the bill, which formed the material pattern for the British act of )Hi3, Lai received an unquestionable indorsement for its practicability and worth." The call npon "other mer cuniile boilieh" to co-operats iu secur ing the paneaie of a national bankrupt law, should meet with an outspoken expression of the wiehes of mer chants with respect to a national bankrupt law. If State legislation, as it px'atn, with all its discrepancies and contradictions roocts with approval, it would be well for trade boards and ex changes formally to say so. If uniform national law npon the subject is de sired, th'we bodies should hasten to make known their wlahos to Congres. MOVE TARIFF TKOI'BLE. The uiontrv.s;t:es of onr high (arid are cutiiu:!ly UHuilosting them selves, f nd are more end more excit ing Oi'poi ition from p rt:.ons of buti nees ti at are opureswd and injuied by ita operation. The wool people a whilo gj were deir.andirg that the tax npon their s'anle should M in creased, because, high as it was, their business was suffering, and more tax nact be piled on to relieve them et their difficulties. Since then farther experience. Las led to an entire revo lution of .view and to tbe dncovery that extreme taxation defeats ij own object and increases the very evils from which ' relief is sought The Philadelphia Ledger repoita tbe wool rorting indue try in that city and dis trict ns depressed, andot 500 porsons employed 300 are spoken cf as out of work. The rta.on for this condition of affair?, i:b given by manufacturers and weaver, is that the. present tariff on raw wr ol ia too high, enabling mar. nfactnrert to Import some gia 'ee of unfinished woolen goods at less than itcoita to make tne same goods here with imported wool. The textile indus tries ere alto athcted br tbe tame overtaxation, and several thou and workmen weavers, winders, epic- tiers, reelers and others are without work in consequence. Thepiospeot of $100,000,000 revenue surplus next year, and the neceudty of providing foreign outlets foi superabundant manufactures, together with injury expeiienred in various occupations through its mischievous operation, inp.ko an curly reform of the tariff a certainty. Hard, stubborn facte, which C inada In finding to be the conse quent of high tariff even mote strik ingly than we have yot done, make re.f iMii no longer a matter of choice hot of necessity, anl the longar m- fiirin Is delayed the morn sweeping and radical It will be whnn it rorai'S. An unsound currency and h mischiev ous lurid are sure to show their evil results In the end. UOHTTIIOLLEIJ riCKAllI) MATH THE JANUABT IHTfcKEAT WILL BE MET Promptly A aiabblnsj Affray Cow. hided by Woman The Hemp bin nd Nashville Railroad. Israelii, to tii irraiL.I Nauhviixs, Ticnn., December 13. Comptroller Pickard says tbe January intereet will be met promptly, though it amounts to $205,000 and the treas ury is now empty. The circular he sent out some vteiks ago is bear ing fruits and collections within the next twenty days will enable tlm (into to pay interest without embarrassment. Pickard believes tho Mate will bo sorely tried within the next two years on account of having to pay $400,0(10 on the new (Torbslt) issue. This Issue is receiv able for taxes only, but represents unt that mnch money to the 8 tale, he Comptroller is of opinion that if tbe General Assembly enacts a law compelling County Courts to pay their own costs in Criminal Courts, the Hi ate will be in no danyer in the future ol becoming embarrassed on account ot a lack el funds to pay her intereet. A charter will be applied for lnoor- S orating the Mempnis and Bristol .ailroad Company. The proposed linn runs from Memphis across the Tennessee river through Hickman and Wayne counties to Naibville, thence eaat lo Bristol, where connec tion will be made for all points east and south. The company wan organ ised by K. W. Cole, Wm. Morrow and others of this city and Memphis. The toad, if built, will do away with the nicioBity existing for a road to Knox ville, such as was proposed in the Crawford road, as tbe line runs di rettly through the section of country contempla'nd by that road. John Biettoii nnd Albart Brown were horribly ecMed this morning in the boiler r om of the Jqurkan build ing. These young men naflb.on cent by B. G. Wood, tin boiler maker, to r air one of the bt ilers in the build ing. They "fie "10 boiler doing their w' when, by some accident, tUa bUbiu frin tho bmlor wbr turned i : t o th one n which the workmen were esg 'ged. Bi f tick wai severely see ded abontthe buck anil around bis walnt, 8' d the skiu taken ff his right arm. Biown's legs were fearfully Resided. Bjtli ineuare suffoiing ter ribly. Mrs. Hue V. Hi'ton, execut''! of J. m Hilton, flUd a bill in the Chan cery Court today Hgaindt ti e Wts'ern Union 'JVIegtaph Ooinpant to recover f5G25and co:its, alleged to bo duo the er-uto of Jam.is Hi ton, deceared. The bill a'l'TPS that Mr. HI'too, at tbe December term, 188fi, of the Supreme Court, obtained a judgment against the Atlantic and Vaciflo Telegraph Company for th above amonnt and ousts. Tho execution was returned nulla h.nti. The bill charges that de lendant Las became po'S''saor of tbe proieily of tbe Atlantic and Paciflc Comp.tny, ai:d (Xrnnlaina lit seeks to recover the debt of the defendants, and prays for tie n-ww.ry relief. A Weleoflvn fnwbldod by a Woman. B J. Ilanaflo, l.itu of tbe Park The a tor and at pre rent of a detective agency, was cowbided by a woman in front of the Mai well II o one touighU Who the female wai nobody knows, aa she literally "cut and ran" before tier Identity could be established. Hani fin's legal wife is employed at the Maxwell, but whether she or some one of Hanafin's diuy female friends did the thrashing is a mystery. Nana Col klabi w. J Rubor, Ike Hotel Proprietor (aricuL to Taa Arraii.. N ABHVii.i.H, Tsnn., December 13. W. J B .kar, proprietor ot the Whits Elephant Hotel, and Ram Cole, nephew of the millionaire, E.W. Cole, had a desperate fight tonight, in which B iker wan rut twice in th neck. Cole was drank, and accused Baker ot hav ing caused his indictment, following this up with a slap. Baker knocked Cole down, and as he stooped to pick up the iirottrate man he was cut with tbe kuife, barely missing the carotid artery. Tbe wounds are painful, but not dangerous. Cole is in jail. A Dtrike Throatvaed tho L, dt If. Ballroad. Nashviixb, Dec. 13. A strike is threatened on the Louisville and Nashville railroad, and it la rumored that from Decatur to Louisville and on all branches hi twen thoas points the emplo) ei wilt etrike at noon tomorrow unless the demaads for im-renfe of time Are conceded. The committee from the men is now in I.o'iisviilo in cniifuI'Viou with tho Ulcers ot the road. The rcsn't is not known at this hour. RKW YOHK DRY HOOIa MARKET. NBWTORK, I)snmbr 13.-Th market hi uiet Irt ncramnd n ron-q'npof Hgtj wtn. r rurdtrlnt lh inilntion ol (nods almo.t ti piMibl. Aff-uts hw advuDocd AndrnnroirKin 10-4 wiJ tfatttim lSo; all othrr widlh, Is. MEMPHIS DAILY APPEALS-TUESDAY, DECEMBER U, 1888. BOODLES, fl'tUtDE 05 TBI1L A9AI74 FOB BRIBERY AIDCORRUi'TlOS. Evidence to Exculpate Him and Prove That He Was an Honest Public .Servant. Nkw Yosx, Det. 13. Tbe trial oj Alderman MiQjade, charged with re ceiving a bribe in connection witH the pus'age of tbe Broadway Surface Itiil rohd frauch s'', was .continued today wi'h tbe bearing rf evidence for the defer sa. W. H. Williams, president, and the Hon. N. A. Nelson, vice pres ident of the cable road, tes'ified thst Iht y did net know ol any offer having been made by thejoompuny to the Al dermen, either directly or indirecrly, for tbe Br odd way frarchit. The company wai authorized to irsue $15, tKK i,000 in stock, and in tne latter part of 1881 did issue $2,000,000 or $3,000, 000 worth of bonds, csnver ed them intoci-sh and deposited with a t'ust company. The trust company also Offered the city $1,000,000 for the franchise. A number ot wit n fuses testified that McQuade favored a street railroad on Broadway btfore he was chosen an Alderman. Ex-President Andrews, cf the cable rad, said he knew of no offer of $750,000, or cf any other sum, to the Aldermen for a frarchiae. The bid of $1,1 00,000 by his ciinpany was intended to cover notot.ly Broadway, but a total of eeventy-eiglu miles of streets. To tho Recorder witness knowl edged signing some bonds lat'T in 1884 iMr. Williuraa bud wine, Mr. 81 aw bad some, about 200 or 300 bonds of 11000 eaoh. The lat-t was in payment for Irgal servic e according to a contract. Wimuts nlao had soma of them, and these were on deposit ith.U e Farmeie' Tina' Ctmpa'iy uh trustee. About $2,000,000 o;tli of bonds were divided amo a i-everal men. To account for McQuade being ' tlneti" ot money, it was shown tlia be had been left a legacy of OKX) iu 1884 This was followed by (.valence as to fie piisoner s gocd character. Testimony was introduced to show that McQuade had been a man ot property fo. yeira. The cualiler of his bank testified that McQnade's lrinRnc Hons for several years had aggregated from $120,000 to $150,1 00 per vear. Ilia bondsman testified that AtcQ iide had mdemnihed him againbt loa by malt leg over to bim property valued at from $40,000 to $5(,,000. Tne secretary of -ttie cable road tes itiud that the bonds were signed in Decmbtr. 1884. but were not leaned till the spring of 1885. John UMeill.oneof tbe indicted A'dermen, denied any knowledge of the "combine;" denied attending the meeting at Fullgraft 's ( dice, or either of the fonr meetings at McLaughlin's ; never before heard that any amount ot money had been oil red to' a fran chise. With Fu'lgrnff. witness once called at McLaughlin's house when the latter was sick, in December, 1884, or in 1885. Via not know the name of the street. On cross-examination, O'Nell aa'd that "Billy" Moloney told him in the City Hall park, in tho summer of 1884, that there was a combination of JL'dermen on railroad matters. Ha could not re member Moloney's message that he believed Jl,0OO,0iA could be bad for the franchise. Witness reluctant ly admitted that be attended tbe secret 9 o'clock meeting of the aldermen. Moloney brought the call to him at 6 o clock in the evening. Did not know or care what the object of the meeting waa. When he wont into tbe mt-e ing he asked and was told the injunction had been dissolved and that Borne one fhe was trying to get another injunction. Never knew the names of tire "com bine " Heard Keeran bed something to do with a "comhioe" on railroad mutters. Did net know that a circu lar, printed as having ben signed by 8ainnel J. Tilden and others as recom mending his election as Alderman, had been distributed in Lis distiict lie said the names read wore dames of general mauagersof tho district or ganization. Witness explained that throughout 1884 there waa a persistent effort to have morning sessions of the Aldermen, Joseph Miner, a uiemher ol the Tam many Hall General Gommi:te of the Fifth District in 1884, testified that McLaughlin waa clmiruiao of the Dem ocratic Sti.ts Convention in June, 1834, Several conferences were held with Mcliiughlin at the latter's house be fore the convention. Other members ol the omtnittee met there to arrange for the fall campaign and to attend tbe National Convention. The meetings were held evenings In May and Jane, 1884. McLaughlin had many callers. Witue s f iund crowds of wen there several times. They were smtetimes in the area ard generally about tbe door. Never mi t any of the Aldermen there. Dr, James W. Lyman, who at'ended MuLnuglilin in his last sickness, was called. He slid McLaugh'iu wait taken sick January 8, 1884. Witness por formed ftti operation on him February 18: li, and Mr Iughlin was conflued to his bed till March lOlh. Mclaughlin after the operation had to huvo an at tendant wherever he went. He went toSamt"ga June 10th aid r-turned 'June 17tti. He made a second trip and spent a few days at W.-ratoga, then went to th north part of Ling Inland June 28 h, remaining there ti l Sep tember. Tuedect r then ou'lined McLsugh HiWh life through 18S5 down to bis death on Long Island, August 2d, dur ing which time the patient wat at bis house In Thirty f.mnb street, and his mother's bona in Ttiitty-ninth street. The doctor lived next do r to Mc Laughlin and his bell was frequently ruug by callers for McLaughlin. The doctor was forced to amend his evi dence in regard to McLaughlin in 1884, asjit waa shown by documentary evidencs tbat McLaughlin was in tbe city at various times in June, Ju y aud August in attendance on Council mtetinirs, State conventions, etc, Me a McSorley, a niece of McLangh Iln.textifitd that Fullgraff called on Mc Laughlin wht e he was ill at kls moth er's bouse between January 1 and 10, 1884 Ex-Alderman Chas. H. Keilly, one ot tbe indicted, contradicted the testi mony of Fullgraff and Duffy in every essential particular, but nothing waa elicited. Indicud ex Alderman Thrs. Oletry, who was ill and did nut teetify at the first trial, denied a'l knowledge of tbe "combine," but aaid he called on McLaughlin during the latter's illness, and insisted on contradicting the servant girl, who swore on Satur day that CUary rang tbe wrong door bell on tl at occasion. Adjourned. A Reverend Father lTtlr a Co ran. Nkwakk. N. J , December IS. At tbe clote of one of the mssws in the Church of O tr Lady cf the Valley yes'erday, tbe Uev. Father fallen, the pastor, spoke at tome length on the qntetion of Sunday observance, which is just cow agitating the people ol Northern New Jersey. He referred pointsdly to tbe glaring violations of tbe law and to tbe extensive tale of Honor to minors. In sneaking of a certain saloon in Orange Valley, he described it in such a manner that tbe members of his congregation cou'd not but know to what place hi re ferred. Suddenly tu ning to the altar he laid bin band npun 1 aud, to the surprise cf the congregation, uttered a cureeon tbesslo in. Tbe matter has been tbe chief tonic of conversation in all the Oangf s today. NATIONAL FIELD TRIALS. TODAY TIIEFIRITOFTIIEtiBANU JUBjCTIOJI MEETIB7U. Kntrlra lor the All A fed Ntabe Drawing and rdr of Kanalna Boalnea Meeting;. IBPBCIAL TO TBI APPIAli. Gbahd Junction, Tknn., December 13. Tbe National Field Trial Club opened their meeting this morning nnder bright and promi -ing auspices. Hpnrtsmeu (roin all sections are here. Triey represent the entire country, from tho shores of the Atlantic to the Pacifl'1, and from the frozen lakes of the North to tbe tepid gulf of tbe South. Gen. W. B. Hh&ttuc, president of the club, came down last night fr m Cincinnati with a bevy of friends in a special car, with tbenirg and eating attachment?. The car is quite a favor ite place ot reaort, where all manner ot good thirg abound. Though pres ident of tbe duo two terms, this is bis first atteudftLCB et its meetings, and if I may be allowed a prediction, ue will be oli dud prts dent agitin and as often as be will accspt. lie ia a clever, whole souled (tontlemtin, full of tbat personal magnetism, which is per fectly irresistible. Mr. O. W. Fuller, of Richmond.Va., one of the judges, and Mr. O. W. Par ish, of Cincinnati, alternate judge, accompanied lien. Shattuc in his car. Among the prominent (p' rtamen pres ent are Maj. "Buck" Key, of Florence, Ala. ; Dr. Rawlings Toung, of Corinth, MisH. ; Maj. J. H. Tr ZHvant, of Texas ; A.J. Rose, cf Texae; II. H. Brigis, of San Francisr o, Cal. ; K. O. Vauhnrn, ol Kansas; George B. Lincoln, of New York; B. Waters, of Chicago; R. F. Greer, cf North Carolina; 8. T. Ham mond, of tbe Ftred and Stream, New York: Dr. N. Ro we, of tbe American Field, Chicano, and a' great many otbera, ' too numerous to mention," from every sic ion. This meeting has brought together the largest number of prominent sportsmen, and as fine a cla-s of dogs, as ever assembled. A business meeting of the club will be held tomorrow night. It is the de termination r f tbe members that this club shall be, as its name implies, na tional, and continue to rack first of all similar orguiiizdions. Many new and important matters will be present ej for the club's conrddsration and a regular "boom" inaugurated. Tbe alleged stake drawing and order of running is as follows: Ben Ilill, owned by B. M. Stephen son, against Beaumont, owned by W. R. Huntington. Gladstone's Boy, owned' by Dr. G. G. Ware, against Lillian, owned by P. H. fc L. Bryson. Don's Dot ( pointer), c weed by J. E. Gill, f gainst Dora (Irinh setter), owned by J. II O'R illy. Pet Gladstone, owner! by P. II. A D. Fryson, against Daisy F. owned by R. M. Dudley. Lady C . wned by B M. Stephen son, againet D in GUdttone, owned by I. H. 4 D. ltryron. Ln.'ra, owned by N. B. Nesbitt, Hgidntt Noble O , owned by B. M. btephenfon. Chickasaw II, owned by P. H. and D Bryaon, aamst Sportsman, owned by Maj. J. U. Mnriian. Minnie 8., owned by B. M. St' phen Fnn, egainat Bridgeport, owntd by E. E Pray. Jack Cade, ownPd by E. V. Halo, ag.r nHt Richmond (politic t), owi.ed by J. E Gill. Mobe, owned by T. L.' Maitin, eg Inst Bjb Gates, ownid by Wbjts Beriford. Patsev D. (Irish ssiter), owned by R. O. Vati Horn, against Gay Glad stone, ownit i by B. P. lLilliday. A vety Inre proportion of the dojs niimiimted w ill start. The weather is fairly good, lint a little cold. The ground is sof1 and traveling heavy ef'er tne show, ami birds are Hcarco. The first series b gan at 0:28 o'clock this morning three miles northeast rf town on ti e Junes farm. Bon II 11 and Bciaum nit ran a close heat, Ben Hill winning on nr se and judqmetit, both rather hIow and working close. Down sixty-iwo minutes. Lillian bent G lads one's Boy in a pretty heat of thinv-one minutes. Hl.e show gocd p:.ce, style and nose. Glad stone's Boy seemed bU.U and lezy, D wn tbirty-ono minutea Daa's Dnt won againet Dora with out making a point, hecause Dora would r ot hack and bad pome de merit. Do , i one hour and thirty five minute. Daisy F. beat Pet Gladitone, having the range, judgment and nose. Pet Gladstone waa tasty aud a l.t'le out lucked. Down one hour and eight minute. Dan Gladstone ard Lady O. ran one hour and thutv tliroe minutes, Lady O. 'having in the opinion of many the best ot the li"at, bat it was given to Dan Gladbtonn. It was a good, keen, cloae face. Both showed good form. Tbe laat heat of ihe day was be tween Lufra and Noble O. It waa won by Nobla O. Neither made an etror. No'rle C. scoaad five olnts to fonr f r Lufra. Both backed and retrieved woll. Diamond at MuHord'a. Postmaater l'hnl With Mobbing l be Mails. Nw Yorx, December 13. George Brown, ntsi.tant postmaster at Ham burg, Ia , was today arraigned before United tStntrw Commissioner Shields, charged with robbing the mails B own when arr'td made a con fession. He left Hamburg in April last, and has traveled nearly around the globe. He was tracked by de tectives, and this morning be was ar rested at the offices of the Shipping Commissioners. He left Liverpool a short time ago and shinped as a sailor under tbe name ot Jackson terbush, Brown was turned over to United States Marshal Bernhardt. He started West with h m this evening. Mutfortr. awl Mnin. Tobaeeo drawers. Locif-viut, Kv., December 13. At the Convention of the Tobacco Grow ers of tbs 8 ate, held at Lexington, Ky , today, it wes decided that the supply and demand should regulate the tobacco production and tMis re lieve the pres- nt distre-s in p-ices. It was recommended that at leapt N) per cent of the crop r.f 1880 should b withheld from the niaiktt indefinitely. - Flue Wftlrbeaitt Mnllord'a. . -- Initial Ulug at Mnlford'A. CAIIPBELL DIVORCE CASE. DR. HKKS G1TES 80IE VALUA BLE TESTIMONY. Lady Campbell's Jloiher Denies Ihat She Hud Any Knowledge Of tbe Engagement. London, December 13. The trial of the Campbell divorce' case was re sumed today. Dr. Hicks testifldd that be made an examination of Lady Campbell and aecertained tbat the lady bad never had a mkot-rriaye. Dr. Hicks, con'inuing, said that the maintenance of relations with the de fendant might have canted pUintiff ecute pain. A woman nrgnt, witm 89 said, be to all appearances virgo iu (acta and yet have conceived. Dr. Barnes corroborated Dr. Hicks. A foot nan employed at Leigh Court testified that Lady Colin'd loom tbere was situated on the side of the build ing opposite tbe room occupied by the Duke of Marlborough. Frank Miles, an artist, and Neptune Bload .both testified tbat they eaw Ldy Coliu Campbell in London r-undv, August 13, 1883, the day on which the defense alleged fhe was at the Pur fleet Hotel with the Duke of Marl borough. Annie Brown denied the statement made by the man eeivant O'Neill tbat ho once called ber attention to stratgi noiBes in tbe dining room cm au oc casion whn Lady Colin aud the Djke cf Marlborough there alone. Neptune Blood testified he bad since the beginning of the trials examined the door of the dining room in Cador- gnn Place, thiough the keyhole ot which the man servant 0'Ncilltesti fled be once eaw plain iff and the Duke of Marlborough in criminal in tercoursa. Wanes said there were flaps over the keyhole on both Bides of the di.or. He looked through, but could not see any object on tne floor six feet awny, nor any article ia the room clearly enough to swear to its identity. Mrs. Blood, Lady Colin's mother, testified that tne engagement between her daughter and Lord Colin was made without ber knowledge. She de nied that she pre sed the marriage. She declared it untrue tbat Lord Colin told her anything about bis health, except that he said he bad an opera tion pel formed. She never would cave given her daughter in marriane to a man in such a Icathfome conuition as Lird Colin was if she had known it. Witness swore that Lady Colin was in her (witness') house Sunday, August 13, 18i3. On cross-examination Mrs. Blood admitted that she wasanxous to break off the marriage between defen dant and her daughter btcause the Campbell family treated her daughter so badly, and added, "It was a wretch edly bad marriage." Witness said she saw no reason why her daughter should not associate with the Duke of Marlborough, who, wit ness declared, was no worse than many others who got off more lightly. Rutisell, counsel for plaintiff, prom ised to conclude the cape for Lady Colin Wednesday. The Judge Eaid he would sit until midnight every day rather than permit Hoe hearing to linger over the holidays. Adjourned THE INTERNATIONAL RAILWAY Exponlllon to Be Held la Paris Tbe United 8late'a Interest. Chicago, Ili, December 13. John W WtJftrnn. ttammiafllnnRr Hantral for the United Sta'es, who proposed inn inn rnttiioiiui iiauway axpoMnon to b held at Paris from May to Octo- hnr him i'HiirH a nrnnnpi'tnn r.fi tbe railway companies, enlisting their . : . . L. . ..u. . : i;u-i it I i. i u ii iu inauro iuni tuo umrwu will bs properly represented. He cites that Grent Britain has asked for six milrs f track rrom to illustrate the operation ol its roaos. Kspect- iru, IIia prnnairinn. Afr. Wpnfon ravr! ' Ai-ttnirr nnimil.tcAi tlironph.int Frani'A eumber 200, Cahine; Min s i ta being on the list of honorary pret-i Ion's. Tho directors lepot ted in November that the prospects cf euccesa ex ceed their most sanguine expectations. .Clglll IX'LUIUllBIUUtTtl UttVB UOru tt nriinfMH fnr fmAiitl rouiifrion. inrlllft ing the Unite! Ststtte, Great Britain, rtosi'iu, iiaiy, opain uuu Dirmi. The Emperor of B f.zd has intimated that he will cordially co-operate. Great activity towardu full representa tion and display pra vails. A TRAIN DIlllILD. Several rawaeua-era Severely In fared. Canton, D. T., Decembar 13. A Milwaukee passenger train, urrth bound, struck a broken rail five miles below Hawarden, at 10:30 o'clock s. rn. The rear coach wa ditched and badly sba'terel. Oblmad, a l qunr dealer at Yankton, was injured about his head. Miss Khodef, of But val ley, Is., had her shou'der injured. Biuce Oliver, of this city, had bis family ou board His small boy W'B ninioued under the car; be hs since been recovered. A six weeks' old child waa thrown violently through a window, but was uninjured. The coach is a bad wrecr, nnd the esr.ape of passengers from dea'b is miracu lous. Ttie balanca of tbe train passed north this afternoon, aud the injured ail Btopped here except Ohlman. None are seriously icjtiied. Boxlon'i Elftfltlon Today. Boston, Maps , Dumber 13. It is certain that a large vote will be polled at tomorrow's municipal election. The triangular contest for ths Mayor slty bttwen Hart (Republican), O'Brien (Democrat), and McNeil (La bor) will be a fierce one. Bjth the Democrats and Republicans appear confident. The Republicans base their bones on the aaaistance of the rouBty Democracy and the labor de fection from the Democratic rauka to McNeil. The labor vote is estimated at 6000. Mulford, Jeweler, 204 Main street, solicits orders from tbe country. ATralaCtoMOveraa Embankment. Pitsboro, Pa., December 13. A Glasgow, Pa , special says: Tbe regu lar passenger trsin on tne Bells Gap railr ad, consisting of one coach, one box car scd a truck laden with lum- Kav Inmnail IVtA ftanV nAtr hunt this morning, and tbe entire train went over a steep embankment. Fourteen passengers were in the conch and four were seriously injured. Their names were rot barned. The coach took fire, but before tbe fUmes obtained much headway they were ex tit'guished. Kulld NlUerat Mnlford'sv, A Mlnlalrr Horn ThleC Galvtom, TkX., December 13. A special from San Antonio to the Asm eaTs: Tbe Rev. Wil iarn Mier, pas'or of ths Bori.et Street Methodi.t Church, wan ariVstoit todav on the charge of horse theft. The case has been sub mitted to the grand jury and the prlS' oner has been refused bail. -FORI- BARBED FENCE W E OEGILL BROTHERS & OO LITTLE ROCK, ARK. The Death of Burns K. Uarlaud. lariniAi to thi rrtL.I Litt-x Rock. Akk . December 13. Information of the death of Rufus K. Garland, e'der hrother r.f Attorney General Garland, wbich ocenned at his home near Petc )H yes erd-y, he- came known in this ci y today and canned nn txprosriion of regret from ail our tit s'nB, n.any r.f whomenjoeil p' rdonl a'.quaintince with the decea-ed. Few uie i iu the Slate were tetter known than Mr. Garland. His death was he rsr.lt cf an attack of crebral menir gitis. He came to Arkauoaa w:th u s paren s f;omTi(it')n Cj., Tonn., whils quite voung, ar,d lias sine its ded here. Daring the course if nn evpnttul life lie held many p'aces of publia trust, in ail of which tout eagaciouaness of purpose which is so characteristic of the r.ODest man was dirplay.id in its fullest teutu, und in dying he has 1 ft "lout prints in the sands ot time" that cm be followed by tbe younger guneratton with great benefit. The polica today captured an o-gan-iied gang of young negro sneak thievts in this city who have been making a practice of it' aling candies from buckets at the Esst Tenncsice depot. Over $00 00:) in foreign capital was invested today in Chattaneoga real es tate. Plans are being piepared for 100 feet of fohr story brick building) to bs ertcted r n Carter street, near tbe People's Hotel, which is now neatly under roof, which wdlbetbe largtBt building in the city. Ilenry M. Rtxnley Mnmmonrd by tbe. Ulna- ol lixiKtuiu to uoiaru. tkw Yobx, December 13 Henry M. Slaaley, the Afidcan explorer, re ceived a cablegram from tbe King of B.lgium, ordering him to return at once. Mr. Star ley was also further advised that this uaexpecttdsummons is cccasioned by the troub e with tne predatory Arabs in the free Congo State. A band-of Arabs under Hen Mohammed, emboldened by tbe ab sence of Stan'ey, have entered the Free Congo State and massacred the earn son at Stanley Fal s. At every village where they found white fam ilies the men were killed and the women ard children car ried away. Tbe Arabs number 1500 men. Attempts have bsen made to check their advance, but without success Ism well acquainted with Ban Mohammed." said Stanley, "hav ing known bim sines 1870, when I made cintrct wilh him ti accompa nymnwi'h force cf men for fifty days, wear 'i.od fiends, atd 1 pre pu-"- Kill. ' r"'- nio t.o fp Absolutely Pure. This pnwder never varlei. A mwvol oi purity, itrenirth and Wbolesomeneta. More eoonomioal than the. ordinary kinds, and oannot be intd in competition with tho mul titude of low teot, short weight alum or phosphate powders. Sold only in cam ROYAL BAKINH POWDKR CO., plfl Wall trft. Nnw YnrV. BIck netdnetie and rcltfre all tho tronhlee Incl dent to a bilious stnto of the system, iirh in Dli tineu, Nni-, I)rowinr. Uintn-M after eating, Pin in the Sule, Ar. While their mow remark iblo tucccsa linn b.nn thown iu curing Hearlachr,)ii'arler'el.lIilcMvcrPIHarefinaIl fkluablc in Conriipntlon, curiDg and prctentiDg lint annoying complaint, while they alio correct III dmonlerl of the ntnmirh. ellTnnlarc the liver uid regulate the bowela. E.en if tb.y only cure! Ache they would be almost priceless to those whs luffer from th! dlslrexing complaints but fortu nately their goodnen does not end here, and tho who once try them will find these little pilla alu ihle In to many waya that they will not be wOliag lo do without them. But after all aick head ACHE (a the bane of eo many lire tbat here re where we. make our great bout. Our pull cur it wbiit othera do nut. . ... parter'a Little liver Pilla am very amall anal very easy to take. One or two pilla make a doae. They are etrictly vegetable and do not grip or purge, but by their gentle action pleaae all who iiKothera. In viala at Si centa; five for II. Sold by drugglata every whe, or sent by mail. CARTER MEDICINE CO., New York City. Holiday Excursion. Mkmphis, Birmingham and Atlantic 1 HaII-RIIAD t'OMl"ANT, L fA-SRNOSR IIRPARTMRNT, f Miurnrs, Xrnn., Dec. 10, lSjd. ) Circular n. i I mm- This Oomnany i l sell ROUND TRIP Tl KVTS du'inn the Holidays at ai On fourili tr for ths roun t Inn. ll.l. ..I ..i. will h Ininhr llrl. 24th. 2fih, 3(Hh,:tlst, an I January 1st, and will be united to return umu januar i, is. . 11. P. KLUtf, Uaneral Arent H il rl'if . . , i t . 1 Tj-wUltfidVjrs ST11 TROYALisa.ij "a J CARTER'S EEMOVAL. We have removed our entire bualneai to Nos. 3T8 &, 3SO Front St., adjoining the Myoar Meld, where wo are receiving a lar, e apgnrtrnent of t'r rlaB'N, lliiicvifa, Whicoiik, Harnem. niwidlery, Ki.,ull of which will he (old at Very Low Prioea. A full line of Horxe ItinnkciN and 1'1 Htba on hand. AU peTfouu in need o' tho above goods will savo money by eziminint; our stock before pur chasing. WOODRUFF & OLIVER, Manufacturers' Agents. FRUITS. Oranges, Malaga Grapes, Apples, ilananas, Lemons, Cranberries. DRIED FRUITS. Pitted Cherries, Evaporated Peaches Citron, Evaporated Pears, German Pears, Lemon Peel, German Cherries, Evaporated Apples Orange Peel, Dates, Kaisins, Prunes, Pine A pple Glace, Figs. NUTS. Almonds, Pecans, Filberts, English Walnuts, Brazil Nuts. Jellies, Preserves, Etc. Shaker Preserves, Canton Ginger, Dundeo Jams and Marmalade, Currant, Raspberry, Strawberry and Peach Jelly by the pound. Apple Butter, Mince Meat, Maplo Syrup, Honey, Maple Sugar, New Molasses, Sugar, Syrup, Plum Pudding. RELISHES. Curry Powder, Celery Sail , Olives, Olive Oil, Capers, Mixed and Plain Pickles, Sweet Siufl'eJ Mangoes, Chow-Cliow, ilolliiml. Pine Apph, Vouni: Anier uii rii..i (.'rui (Jiioc-e. Salad Hii'-VLi. Di-vile't I J am. Worcesteisijiro Saute, I nuato Cat sup, Mustard, Pepper Sauce, Sage, Thyme, Sweel Margorium, Summer Savorj FARINACilOUS GOODS Buckwheat Flour, Graham Flour, Dried Corn, Farina. Tapioca. Sago, Corn Starch, LentPls, Rolled Avena, Oatmeal. Cracked Wheat, Split Peas, Rice, White Peas, May Beans, Farinoca, Hominy, Grits, Barley, Gretn Kern. CALIFORNIA FRUITS. White Peaol es, A pricota, Epg Plum Yellow Psaches, Grapea, Nectarines, Green Gages, Cherries, Pino Apples, Goosebjirics, Bartlett Pears. "VEGETABLES. Asparagus, Baked Beans, Peas, String and Stringlesa Beans, Corn, Tomatoes, Okra snd Tomatoes, Okra Succatash, Pumpkin. Canned Fish and Meats. t i . Hi... T . 1 . .1 n l, iiODSters, oioaiorM. iuviiuu viauo, Finland Haddies, Salmon, Sardines, Mackerel, Shrimps, Russian Cavier, Cove Oysters, Pijisfeer,, Chip Beef, Ox Tonguo, Canned Beet. SUNDRIES. Gelatine, Flavoring Extraots, least 1'owder, iilanks s uana-maae Candy. Larrabee & Kennedy's Cakes and PrnfL-rtru Creamery Butler. Sweet Cider, Boston Brown Bread, Deep ScaCod- nsn, blicilcd Aimenas. VALUABLE PLANTATION, jimii.. tmnaid Public lu. For Lease for Five Years. TITG will le'e tbat valuable cisntatios J T". 1. A M wAII I c a nr. A PM tk.. miles below Onceola. Ark for a term of firs years. One thousand sores of oleared land, with resident tenanrs who own their teams. The landinr and rereiTina- point in ordinary water for Osceola and a lar.e neighborhood. Ibe United States fleet anohnrtd in front. The I'n'ted States Oovernmont will exp-nd from tlliO.000 to S tiil.OOO the eorninn season on river i in i m i o ut it u v .u i ynr u.u " -this point, mak'n it a most valuable mer cantile print. The tuhlie gin will eontrol lOu.i bales of euMom cotton. Good residents and healthy location. No ether such orer tunitv fnr a live hu.lneaa man can be fount on the river. Aoply to . thus. n. l..ivn v"v, or B. B. WADUBLk, Memphis. . BElDQTJtBTltRS FOB CORRUGATED IRON SIDING And Iron Roofing- sn Flrei, Wind Water sad 1lRha'iBa? prool. Suitable for all kinds ot build a(s J For prices and estimates a factory 'rates i eall on or address MEMPHIS METAL A WOOD UV O CO., i i A W0 Main it., and 21 A 23 Mvilbarry -; MBMPUIB.TKNN, Headquarters (or Iron feneea and Oestine, UatTauUediron Corntoe.IU ftoofj A blOTea iilii! Iiiil;; Ultimo. xml | txt
http://chroniclingamerica.loc.gov/lccn/sn84024448/1886-12-14/ed-1/seq-4/ocr/
CC-MAIN-2014-35
refinedweb
6,984
74.49
Support and discussion about lifelines. this is what I meant by the hazard at t, for instance. I could not find where it was implemented, is this equivalent to thethis is what I meant by the hazard at t, for instance. I could not find where it was implemented, is this equivalent to the from math import exp def hazard( phdata, coef, baseline, i, t ): cov = phdata.iloc[i].drop(labels=['censored?, 'eventdate']) base = baseline.at[float(t),'baseline hazard'] haz= base*exp(cov.dot(coef)) return haz predict_partial_hazard(X)? It looks like you want the hazard per subject over time (not the cumulative hazard). The most appropriate way is to do something like cph.predict_cumulative_hazard(phdata).diff() as the cumulative hazard and the hazard are related in that manner. Using predict_cumulative_hazard is helpful since it takes care of any strata arguments, and de-meaning necessary. You mentioned to me privately about why I subtract the mean of the covariates in the prediction methods. The reason is that the algorithm is computed using demeaned data, and hence the baseline hazard "accounts" for the demeaned data and grows or shrinks appropriately (I can't think of a better way to say this without a whiteboard/latex). From the POV of the hazard then, the values are the same. However, the log-partial hazard and the partial hazard will be different. This is okay, as there is no interpretation of the (log-)partial hazard without the baseline hazard (another way to think about this: it's unit-less). The only use of the (log-)partial hazard is determining rankings. That is, the multiplying by the baseline hazard is necessary to recover the hazards. Hi all, I'm having issues with convergence for the CoxPHFitter in lifelines that I'm not seeing in R. It gives me this message "ConvergenceError: Convergence halted due to matrix inversion problems. Suspicion is high collinearity. Please see the following tips in the lifelines documentation: Matrix is singular." Even when I reduce the dataset to just the time at observation, whether or not event happened, and a single covariate. Graphically I have verified that there is not a perfect decision boundary - I have also modeled this in R and it has worked perfectly. When looking at the algorithm step output, it does look like that Newton algorithm is diverging: Iteration 1: norm_delta = 2.29694, step_size = 0.9500, ll = -27814.17290, newton_decrement = 3481.08865, seconds_since_start = 0.0 Iteration 2: norm_delta = 5.84762, step_size = 0.9500, ll = -36925.79270, newton_decrement = 37483.21855, seconds_since_start = 0.0 Iteration 3: norm_delta = 108.73423, step_size = 0.7125, ll = -40227.22948, newton_decrement = 210617.17243, seconds_since_start = 0.1 Iteration 4: norm_delta = 14575.06691, step_size = 0.2095, ll = -1076963.03641, newton_decrement = 106456100.74164, seconds_since_start = 0.1 fit. For example, cph.fit( ..., step_size=0.30)(or decrease more if necessary). I would appreciate if you could share the dataset with me as well (privately, at cam.davidson.pilon@gmail.com), as datasets that fail convergence as useful to try new methods against. @MattB27 the equation on page 7 of the pdf is not what is implemented. Recall, the MLE, I take the log, then differentiate. numer and denom in the code refer to the numerator and denominator in the fraction here: which is the resulting equation after logging + differentiating the eq on page 7 What's the best way to save a lifelines model? (or is this not possible)? I'd like to automate the model to make predictions daily, but retrain only weekly. The model in question is a lognormal AFT. I tried to use joblib, but it threw a PicklingError: PicklingError: Can't pickle <function unary_to_nary.<locals>.nary_operator.<locals>.nary_f at 0x1a378e9f28>: it's not found as autograd.wrap_util.unary_to_nary.<locals>.nary_operator.<locals>.nary_f If you have an individual, who has the 'death' event, but then becomes alive again, and then has a 'death' event again. How do you treat this? should you use a time based model, and record the death event something like this [t0 - t1, death] [t2 - t3, death], or do you not record the death event but still you a time based model, recording a gap in between the 'observations' [t0 - t1, t2-t3, death] OR could you use a standard(non-temportal) model and treat them as separate individuals? What would the mathematical ramifications be to use a standard model like this?
https://gitter.im/python-lifelines/Lobby?at=5ce520790ac9852a951e5448
CC-MAIN-2021-04
refinedweb
731
60.31
30 October 2012 10:09 [Source: ICIS news] SINGAPORE (ICIS)--Here is Tuesday’s end-of-day ?xml:namespace> CRUDE: Dec WTI $85.64/bbl, up 10 cents/bbl; Dec BRENT $109.38/bbl, down 6 cents/bbl Crude futures recouped some losses in afternoon trade, with WTI moving into positive territory, while ICE Brent was trading at a small discount. Crude values firmed on reports that damage from “super storm” NAPHTHA: $964.00-965.00/tonne CFR Open-spec prices for the first half of December contract extended gains in the afternoon. The spread between the second-half December contract and the second-half March contract was done at $40/tonne. BENZENE: $1,295-1,315/tonne FOB Market players covering short positions placed higher bids, while supply remains tight in the region. A deal for a December-loading cargo was concluded at $1,297/tonne FOB Korea, while a January-loading lot changed hands at $1,272/tonne FOB Korea. Discussions for November-loading lots remained scarce. TOLUENE: $1,215-1,230/tonne FOB Short-covering pushed up prices. Bids for December-loading lots were at $1,205-1,215/tonne FOB ETHYLENE: $1,340-1,370/tonne CFR NE Asia, steady Trade was hindered by a wide big-offer gap, with bids capped in the low- $1,300/tonne CFR China levels on the back of depressed derivative pricing. Suppliers however, were not in a hurry to sell below $1,350-1,370/tonne CFR China on account of limited spot availability. PROPYLENE: $1,350-1,360/tonne CFR NE Asia, stable Discussions were thin in the afternoon. Selling ideas remained at around $1,360-1,370/tonne CFR NE Asia, while buying ideas were at around $1,350/tonne CFR NE Asia
http://www.icis.com/Articles/2012/10/30/9608549/evening-snapshot-asia-markets-summary.html
CC-MAIN-2014-35
refinedweb
296
55.64
react-native-sortable-listview Drag drop capable wrapper of ListView for React Native. Allows for dragging and dropping of rows with automatic scrolling while dragging. Add it to your project - Run npm install react-native-sortable-listview --save import SortableListView from 'react-native-sortable-listview' Demo Basic usage Example Props SortableListView passes through all the standard ListView properties to ListView, except for dataSource. The renderRow method must render a component that forwards onLongPress and onPressOut methods to a Touchable* child component. Calling the onLongPress method will enable the drag and drop on the row and onPressOut will cancel it. You can also apply the default behaviour by spreading the sortHandlers prop (e.g. <TouchableHightlight {...this.props.sortHandlers} >..) onRowMoved(Function) - should return a function that is passed a single object when a row is dropped. The object contains three properties from, to, and row. fromand toare the order indexes being requested to move. rowis all the info available about the row being dropped. data(Object) - Takes an object. rowHasChanged(Function) - Takes an function that is called to compare row data. It is passed the new row data and a shallow copy of the previous row data. This is necessary to define if row data is not immutible for row changes to correctly propagate, if your row data is immutable DO NOT DEFINE, see #28 for reasons why. order(Array) (optional) - Expects an array of keys to determine the current order of rows. sortRowStyle(Object) (optional) - Expects a styleobject, which is to be applied on the rows when they're being dragged. disableSorting_(boolean) (optional) - When set to true, all sorting will be disabled, which will effectively make the SortableListView act like a normal ListView. onMoveStart(Function) (Optional) - Register a handler to be called when drag start. onMoveEnd(Function) (Optional) - Register a handler to be called when move is completed. onRowActive(Function) (Optional) - Register a handler to be called when row is activated, return a object contains three properties rowData, touchand layout. rowDatais the data info of activated row, layoutis the layout info of the activated row, touchis the nativeEventof long press onMoveCancel(Function) (Optional) - Register a handler to be called when move is canceled, that is the row is activated on long press and then released without any move. activeOpacity(Number) (Optional) - Sets opacity of an active element. Default value: 0.2. limitScrolling_(boolean) (optional) - When set to true, scrolling will be disabled when a row is active (sorting). Default is false. moveOnPressIn_(boolean) (optional) - When set to true, longPress delay is eliminated. Default is false. ListViewComponent_(Function) (optional) - A custom ListView component to be used instead of React-Native's ListView. disableAnimatedScrolling_(boolean) (optional) - When set to true, scrolling will no longer animate. Default is false. Strongly recommend set it to true., see #97 for more context. methods scrollTo(...args)- Scrolls to a given x, y offset, either immediately or with a smooth animation. See ScrollView's scrollTo method.
https://reactnativeexample.com/drag-drop-capable-wrapper-of-listview-for-react-native/
CC-MAIN-2021-17
refinedweb
489
57.87
Main class of the module, inherits from StelModule. More... #include <Scenery3d.hpp> Main class of the module, inherits from StelModule. Manages initialization, provides an interface to change Scenery3d properties and handles user input Definition at line 51 of file Scenery3d.hpp. Detect or show the configuration GUI elements for the module. This is to be used with plugins to display a configuration dialog from the plugin list window. Reimplemented from StelModule. Called before the module will be delete, and before the openGL context is suppressed. Deinitialize all openGL texture in this method. Reimplemented from StelModule. Execute all the drawing functions for this module. Reimplemented from StelModule. Forces a redraw of the cubemap. Return the value defining the order of call for the given action For example if stars.callOrder[ActionDraw] == 10 and constellation.callOrder[ActionDraw] == 11, the stars module will be drawn before the constellations. Reimplemented from StelModule. Returns the current cubemapping mode. Gets the SceneInfo of the scene that is currently being displayed. Check SceneInfo::isValid to determine if a scene is displayed. Returns the ID of the currently loaded scene, or an null string if nothing is displayed. Returns a StoredView that represents the current observer position + view direction. Label and description are empty. Gets the SceneInfo of the scene that is currently in the process of being loaded. Check SceneInfo::isValid to determine if a scene is loaded. Definition at line 258 of file Scenery3d.hpp. Returns the ID of the currently loading scene, or null if nothing is being loaded. Returns the current shadow filter quality. Walk/Fly Navigation with Ctrl+Cursor and Ctrl+PgUp/Dn keys. Pressing Ctrl-Alt: 5x, Ctrl-Shift: 10x speedup; Ctrl-Shift-Alt: 50x! To allow fine control, zoom in. If you release Ctrl key while pressing cursor key, movement will continue. Reimplemented from StelModule. Initialize itself. If the initialization takes significant time, the progress should be displayed on the loading bar. Implements StelModule. This starts the scene loading process. This is asynchronous, this method returns after metadata loading. This starts the scene loading process. This is asynchronous, this method returns after metadata loading. This signal is emitted from another thread than this QObject belongs to, so use QueuedConnection. Performs a relative translation of the viewer's position.). Clears the shader cache, forcing a reload of shaders on use. Sets the cubemapping mode. Sets the size used for cubemap rendering. For best compatibility and performance, this should be a power of 2. Use this to set/get the enableBumps flag. If set to true, bump mapping is enabled for the 3D scene. Set to true to show some rendering debug information. Sets the state of the cubemap lazy-drawing mode. Set to true to show the current standing positin as text on screen. Enables/Disables the plugin. Use this to set/get the enableShadows flag. If set to true, shadow mapping is enabled for the 3D scene. Set to true to add an additional light source centered at the current position, useful in night scenes. Sets the interval for cubemap lazy-drawing mode. When true, only the face which currently is most dominantly visible is updated while moving. Sets the shadow filter quality. Sets the size used for shadowmap rendering. For best compatibility and performance, this should be a power of 2. Sets the range of the torchlight. Sets the strength of the additional illumination that can be toggled when pressing a button. If true, only 1 shadow cascade is used, giving a speedup. Changes the current view to the given view. JD is updated only if view contains valid data and setDate is true. Display text message on screen, fade out automatically. Shows the stored view dialog. Update the module with respect to the time. Implements StelModule. Sends the progressReport() signal, which eventually updates the progress bar. Can be called from another thread.
http://stellarium.org/doc/head/classScenery3d.html
CC-MAIN-2018-09
refinedweb
643
62.04
$ cnpm install @eliumhq/elium-i18n In order to be able to push the POT (template file containing all the sentences to translate), you need to install the Transifex client. Please follow the instructions below to install it on macOS / Linux. If you need to install it on another platform, please follow their installation guide. sudo easy_install pip sudo pip install transifex-client These commands will install the executable tx that we are goin to use to push and pull translations from Transifex. The Transifex client ( tx) must be configured in two ways. The credentials used for the remote project are stored in .transifexrc in your [] hostname = password = $ASK_AROUND_YOU$ token = $ASK_AROUND_YOU$ username = api Transifex needs to be configured by project as well. cat .tx/config [main] host = [$PROJECT$] file_filter = translations/<lang>/$NAME$.po source_file = translations/$NAME$.pot source_lang = en type = PO The normal procedure can be described as follows: Sentences to translate are extracted using our AST Parser that parses JS/JSX files and match the following structures. import i18n from 'libs/i18n' const text = i18n.t('My string to translate') || t('My string to translate when using the HOC translate()') const interpolation = t('{{ number }} is my number', { number: 42 }) const plural = t('one object', { plural: '{{ count }} objects', count }) const context = t('string with context', { context: 'ctx' }) const comp = ( <Translate> <span> This <b>will be</b> <i>extracted</i> </span> </Translate> )
https://developer.aliyun.com/mirror/npm/package/@eliumhq/elium-i18n
CC-MAIN-2020-24
refinedweb
230
62.17
Question #1 – Swift 1.0 or later What’s a better way to write this for loop with ranges? Answer: Question #2 – Swift 1.0 or later What’s the value of tutorial1.difficulty and tutorial2.difficulty? Answer: tutorial1.difficulty is 1, whereas tutorial2.difficulty is 2. Question #3 – Swift 1.0 or later view1 is declared with var, and view2 is declared with let. What’s the difference here, and will the last line compile? import UIKit var view1 = UIView() view1.alpha = 0.5 let view2 = UIView() view2.alpha = 0.5 // Will this line compile? Answer: view1 is a variable and can be re-assigned to a new instance of UIView. With let you can assign a value only once, so the following code doesn’t compile: view2 = view1 // Error: view2 is immutable However, UIView is a class with reference semantics, so you can mutate the properties of view2 (which means the last line will compile): let view2 = UIView() view2.alpha = 0.5 // Yes! Question #4 – Swift 1.0 or later This code sorts an array of names alphabetically and looks complicated. Simplify it and the closure as much as you can. let animals = [“fish”, “cat”, “chicken”, “dog”] let sortedAnimals = animals.sort { (one: String, two: String) -> Bool in return one < two } Answer: 1- let sortedAnimals = animals.sort { (one, two) -> Bool in return one < two } 2- let sortedAnimals = animals.sort { return $0 < $1 } 3- let sortedAnimals = animals.sort(<) Question #5 – Swift 1.0 or later This code creates two classes, Address and Person, and it creates two instances to represent Ray and Brian. Suppose Brian moves to the new building across the street, so you update his record like this: brian.address.fullAddress = “148 Tutorial Street” What’s going on here? What’s wrong with this? Answer: Ray also moved to the new building! Address is a class and has reference semantics, so headquarters is the same instance, whether you access it via ray or brian. Changing the address of headquarters will change it for both. Can you imagine what would happen if Brian got Ray’s mail or vice versa? :] The solution is to create a new Address to assign to Brian, or to declare Address as a struct instead of a class. Source : Raywenderlich
http://mycodetips.com/ios/swift-technical-interview-questions-answers-1283.html
CC-MAIN-2017-22
refinedweb
376
68.97
1. Restructured Text (reST) and Sphinx CheatSheet¶ Overview This page describes some of the RST and Sphinx syntax. It is based on resource found at Sphinx , Docutils and more generally software documentation written with Sphinx. This is not an exhaustive description but it should allow you to start and create already nice documentation. Contents - Restructured Text (reST) and Sphinx CheatSheet - Introduction - Text Formatting - What are directives - Inserting code and Literal blocks - Tables - Include other RST files with the toctree directive - Python software - Images and figures - Boxes - Others - Useful extensions 1.1. Introduction¶ The reStructuredText (RST) syntax provides an easy-to-read, what-you-see-is-what-you-get plaintext markup syntax and parser system. However, you need to be very precise and stick to some strict rules: - like Python, RST syntax is sensitive to indentation ! - RST requires blank lines between paragraphs This entire document is written with the RST syntax. In the right sidebar, you should find a link show source, which shows the RST source code. 1.2. Text Formatting¶ 1.2.1. Inline markup and special characters (e.g., bold, italic, verbatim)¶ There are a few special characters used to format text. The special character * is used to defined bold and italic text as shown in the table below. The backquote character ` is another special character used to create links to internal or external web pages as you will see in section Internal and External Links. The double backquote is used to enter in verbatim mode, which can be used as the escaping character. There are some restrictions about the * and `` syntax. They - cannot not be nested, - content may not start or end with whitespace: * text* is wrong, - it must be separated from surrounding text by non-word characters like a space. The use of backslash is a work around to second previous restrictions about whitespaces in the following case: - this is a *longish* paragraph is correct and gives longish. - this is a long*ish* paragraph is not interpreted as expected. You should use this is a long\ *ish* paragraph to obtain longish paragraph In Python docstrings it will be necessary to escape any backslash characters so that they actually reach reStructuredText. The simplest way to do this is to use raw strings by adding the letter r in front of the docstring. 1.2.2. Headings¶ In order to write a title, you can either underline it or under and overline it. The following examples are correct titles. ***** Title ***** subtitle ######## subsubtitle ********************** and so on Two rules: - If under and overline are used, their length must be identical - The length of the underline must be at least as long as the title itself Normally, there are no heading levels assigned to certain characters as the structure is determined from the succession of headings. However, it is better to stick to the same convention throughout a project. For instance: - # with overline, for parts - * with overline, for chapters - =, for sections - -, for subsections - ^, for subsubsections - “, for paragraphs 1.2.3. Internal and External Links¶ - In Sphinx, you have 3 type of links: - External links (http-like) - Implicit links to title - Explicit links to user-defined label (e.g., to refer to external titles). 1.2.3.1. External links¶ If you want to create a link to a website, the syntax is `<>`_ which appear as . Note the underscore after the final single quote. Since the full name of the link is not always simple or meaningful, you can specify a label (note the space between the label and link name): `Python <>`_ The rendering is now: Python. Note If you have an underscore within the label/name, you got to escape it with a ‘\’ character. 1.2.3.2. Implicit Links to Titles¶ All titles are considered as hyperlinks. A link to a title is just its name within quotes and a final underscore: `Internal and External links`_ This syntax works only if the title and link are within the same RST file. If this is not the case, then you need to create a label before the title and refer to this new link explicitly, as explained in Explicit Links section. 1.2.3.3. Explicit Links¶ You can create explicit links within your RST files. For instance, this document has a label at the top called rst_tutorial, which is specified by typing: .. _rst_tutorial: You can refer to this label using two different methods. The first one is: rst_tutorial_ The second method use the ref role as follows: :ref:`rst_tutorial` With the first method, the link appears as rst_tutorial, whereas the second method use the first title’s name found after the link.. You can jump there by writting :ref:`introduction`, which appears as: Why Sphinx and for which users ?. Note Note that if you use the ref role, the final underscore is not required anymore. 1.2.4. List and bullets¶ The following code: * This is a bulleted list. * It has two items, the second item uses two lines. (note the indentation) 1. This is a numbered list. 2. It has two items too. #. This is a numbered list. #. It has two items too. gives: - This is a bulleted list. - It has two items, the second item uses two lines. (note the indentation) - This is a numbered list. - It has two items too. - This is a numbered list. - It has two items too. Note if two lists are separated by a blanck line only, then the two lists are not differentiated as you can see above. 1.3. What are directives¶ Sphinx and the RST syntax provides directives to include formatted text. As an example, let us consider the code-block syntax. It allows to insert code (here HTML) within your document: .. code-block:: html :linenos: <h1>code block example</h1> Its rendering is: Here, code-block is the name of the directive. html is an argument telling that the code is in HTML format, lineos is an option telling to insert line number and finally after a blank line is the text to include. Note that options are tabulated. 1.4. Inserting code and Literal blocks¶ 1.4.1. How to include simple code¶ This easiest way to insert literal code blocks is to end a paragraph with the special marker made of a double coulumn ::. Then, the literal block must be indented: This is a simple example:: import math print 'import done' or: This is a simple example: :: import math print 'import done' gives: This is a simple example: import math print 'import done' 1.4.2. code-block directive¶ By default the syntax of the language is Python, but you can specify the language using the code-block directive as follows: .. code-block:: html :linenos: <h1>code block example</h1> produces 1.4.3. Include code with the literalinclude directive¶ Then, it is also possible to include the contents of a file as follows: .. literalinclude:: filename :linenos: :language: python :lines: 1, 3-5 :start-after: 3 :end-before: 5 For instance, the sample.py file contents can be printed: 1.5. Tables¶ There are several ways to write tables. Use standard reStructuredText tables as explained here. They work fine in HTML output, however, there are some gotchas when using tables for LaTeX output. The rendering of the table depends on the CSS/HTML style, not on sphinx itself. 1.5.1. Simple tables¶ Simple tables can be written as follows: +---------+---------+-----------+ | 1 | 2 | 3 | +---------+---------+-----------+ which gives: Size of the cells can be adjusted as follows: +---------------------+---------+---+ |1 | 2| 3 | +---------------------+---------+---+ renders as follows: This syntax is quite limited, especially for multi cells/columns. 1.5.2. Multicells tables, first method¶ A first method is the following syntax: +------------+------------+-----------+ | Header 1 | Header 2 | Header 3 | +============+============+===========+ | body row 1 | column 2 | column 3 | +------------+------------+-----------+ | body row 2 | Cells may span columns.| +------------+------------+-----------+ | body row 3 | Cells may | - Cells | +------------+ span rows. | - contain | | body row 4 | | - blocks. | +------------+------------+-----------+ gives: 1.5.3. Multicells table, second method¶ The previous syntax can be simplified: ===== ===== ====== Inputs Output ------------ ------ A B A or B ===== ===== ====== False False False True False True ===== ===== ====== gives: Note table and latex documents are not yet compatible in sphinx, and you should therefore precede them with the a special directive (.. htmlonly::) 1.5.4. The tabularcolumns directive¶ 1.5.5. The csv-table directive¶ Finally, a convenient way to create table is the usage of CSV-like syntax: .. csv-table:: a title :header: "name", "firstname", "age" :widths: 20, 20, 10 "Smith", "John", 40 "Smith", "John, Junior", 20 that is rendered as follows: 1.6. Include other RST files with the toctree directive¶ Sooner or later you will want to structure your project documentation by having several RST files. The toctree directive allows you to insert other files within a RST file. The reason to use this directive is that RST does not have facilities to interconnect several documents, or split documents into multiple output files. The toctree directive looks like .. toctree:: :maxdepth: 2 :numbered: :titlesonly: :glob: :hidden: intro.rst chapter1.rst chapter2.rst It includes 3 RST files and shows a TOC that includes the title found in the RST documents. Here are a few notes about the different options - maxdepth is used to indicates the depth of the tree. - numbered adds relevant section numbers. - titlesonly adds only the main title of each document - glob can be used to indicate that * and ? characters are used to indicate patterns. - hidden hides the toctree. It can be used to include files that do not need to be shown (e.g. a bibliography). The glob option works as follows: .. toctree:: :glob: intro* recipe/* * Note also that the title that appear in the toctree are the file’s title. You may want to change this behaviour by changing the toctree as follows: .. toctree:: :glob: Chapter1 description <chapter1> So that the title of this section is more meaningful. 1.7. Python software¶ Sphinx can be used to create generic documentation, or software documentation dedicated to Python, but not only (can C, C++, ...). Here, we’ll focus on Python itself. 1.7.1. Auto-document your python code¶ Let us suppose you have a python file called sample.py with a function called square. The function’s code is : Using the autofunction : .. currentmodule:: sample .. autofunction:: square Gives - square(a)[source]¶ short description of the function square longish explanation: returns the square of a: Here, we need to specify in which module should be found the function square, hence the .. module::sample directive. You can use autoclass and automodule in the same way. Using the module directive also creates an index (see top right of this page) so it is worth specifying more information using platform and synopsis options for example: .. module:: sample :platform: Unix, Windows :synopsis: sample of documented python code The results will be shown in a module section (link in top right panel). Note the directive module should be use only once for a given module. Warning the python code must be in the PYTHONPATH. 1.7.2. python docstrings¶ In a python shell, when you type a statement, it is preceeded by the >>> sign. The results are printed without it. For instance: >>> a = 1 1 If you want to copy and paste this code, you will get errors since the >>> sign is not part of the syntax. There is a javascript solution to hide it in the Useful extensions section. 1.8. Images and figures¶ 1.8.1. Include Images¶ Use: .. image:: stars.jpg :width: 200px :align: center :height: 100px :alt: alternate text to put an image 1.8.2. Include a Figure¶ .. figure:: stars.jpg :width: 200px :align: center :height: 100px :alt: alternate text :figclass: align-center figure are like images but with a caption and whatever else youwish to add .. code-block:: python import image gives The option figclass is a CSS class that can be tuned for the final HTML rendering. 1.9. Boxes¶ 1.9.1. Colored boxes: note, seealso, todo and warnings¶ There are simple directives like seealso that creates nice colored boxes: See also This is a simple seealso note. created using: .. seealso:: This is a simple **seealso** note. You have also the note directive: Note This is a note box. with .. note:: This is a **note** box. and the warning directive: Warning note the space between the directive and the text generated with: .. warning:: note the space between the directive and the text There is another todo directive but requires an extension. See Useful extensions 1.9.2. Topic directive¶. 1.10. Others¶ 1.10.2. Substitutions¶ Substitutions are defined as follows: .. _Python: and to refer to it, use the same syntax as for the internal links: just insert the alias in the text (e.g., Python_, which appears as Python_ ). A second method is as follows: .. |longtext| replace:: this is a very very long text to include and then insert |longtext| wherever required. 1.10.3. glossary, centered, index, download and field list¶ 1.10.3.2. glossary¶ .. glossary:: apical at the top of the plant. gives - apical - at the top of the plant. 1.10.3.4. download¶ :download:`download samplet.py <sample.py>` gives download sample.py 1.10.4. Footnote¶]. 1.10.5. Citations¶ Citation references, like [CIT2002] may be defined at the bottom of the page: .. [CIT2002] A citation (as often used in journals). and called as follows: [CIT2002]_ 1.10.6. More about aliases¶ Directives can be used within aliases: .. |logo| image:: stars.jpg . 1.10.7. Intersphinx¶ When you create a project, Sphinx generates a file containing an index to all the possible links (title, classes, functions, ...). You can refer to those index only if Sphinx knowns where to find this index. THis is possible thanks to the intersphinx option in your configuration file. For instance, Python provides such a file, by default Sphinx knows about it. The following code can be found at the end of a typical Sphinx configuration file. Complete it to your needds: # Example configuration for intersphinx: refer to the Python standard library. intersphinx_mapping = {'': None, } 1.10.8. file-wide metadata¶ when using the following syntax: :fieldname: some contents some special keywords are recognised. For instance, orphan, nocomments, tocdepth. An example of rendering is the toctree of top of this page. 1.10.9. metainformation¶ Specifies the author of the current section.: .. sectionauthor:: John Smith <js@python.org> By default, this markup isn’t reflected in the output in any way, but you can set the configuration value show_authors to True to make them produce a paragraph in the output. 1.10.10. contents directives¶ 1.11. Useful extensions¶ In the special file called conf.py, there is a variable called extensions. You can add extension in this variable. For instance: extensions = [- 'easydev.copybutton', 'sphinx.ext.autodoc', 'sphinx.ext.autosummary', 'sphinx.ext.coverage', 'sphinx.ext.graphviz', 'sphinx.ext.doctest', 'sphinx.ext.intersphinx', 'sphinx.ext.todo', 'sphinx.ext.coverage', 'sphinx.ext.pngmath', 'sphinx.ext.ifconfig', 'matplotlib.sphinxext.only_directives', 'matplotlib.sphinxext.plot_directive', ] 1.11.1. pngmath: Maths and Equations with LaTeX¶ The extension to be added is the pngmath from sphinx: extensions.append('sphinx.ext.pngmath') In order to include equations or simple Latex code in the text (e.g., ) use the following code: :math:`\alpha > \beta` Warning The math markup can be used within RST files (to be parsed by Sphinx) but within your python’s docstring, the slashes need to be escaped ! :math:`\alpha` should therefore be written :math:`\\alpha` or put an “r” before the docstring Note also, that you can easily include more complex mathematical expressions using the math directive: .. math:: n_{\mathrm{offset}} = \sum_{k=0}^{N-1} s_k n_k Here is another: It seems that there is no limitations to LaTeX usage: 1.11.2. TODO extension¶ Similarly to the note directive, one can include todo boxes bu it requires the sphinx.ext.todo extension to be added in the conf.py file by adding two lines of code: extensions.append('sphinx.ext.todo') todo_include_todos=True Todo a todo box 1.10.1. Comments¶ Comments can be made by adding two dots at the beginning of a line as follows:
http://www.thomas-cokelaer.info/tutorials/sphinx/rest_syntax.html
CC-MAIN-2018-22
refinedweb
2,683
64.81
Hi,On Mon, 15 Aug 2005, john stultz wrote:> > I think most of this is premature cleanup. As it also changes the logic in > > small ways, I'm not even sure it qualifies as a cleanup.> > Please, Roman, I'm spending quite a bit of time breaking this up into> small chunks specifically to help this discussion. Rather then just> stating that the logic is changed in small ways, could you please be> specific and point to where that logic has changed and we can fix or> discuss it.Well, part of the problem is that you didn't really explain, why your logical are better in any way. You broke them out of your big patch and they lose their context.It's probably better to first to understand and agree on the functional changes, moving code around can still be done afterwards.> > For the rest I can't agree on to move everything that aggressively into > > the ntp namespace. The kernel clock is controlled via NTP, but how it > > actually works has little to do with "network time". > > Eh? The adjtimex() interface causes a small adjustment to be added or> removed from the system time each tick. Why should this code not be put> behind a clear interface?I don't mind the clear interface...> > Some of the > > parameters are even private clock variables (e.g. time adjustment, phase), > > which don't belong in any common code. (I'll expand on that in the next > > mail.)> > Again, I'm not understanding your objection. Its exactly because the> time_adjust and phase values are NTP specific variables that I'm trying> to move them from the timer.c code into ntp.cThe point is you're starting at the wrong point, first we need a clean clock interface, only then should we change the ntp code to it.(More again in the next mail.)bye, Roman-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
https://lkml.org/lkml/2005/8/16/291
CC-MAIN-2017-13
refinedweb
344
73.68
In this section we will discuss about the Reader class in Java. Reader class is an abstract class in java.io package provided for reading the character streams. This class is a super class of all the classes which are involved in or to facilitate to read (input) the character streams. Classes descended from this class may overrides the methods of this class but the method read(char[], int, int) and close() must be implemented by the subclasses. This class can not be instantiated directly. Constructor of Reader Methods of Reader class Methods that must be implemented by its subclasses are as follows : Commonly used methods of this class are as follows : Example : An example of Reader class is given here which demonstrate that how character streams reader can be created and how the characters can be read from the stream. In this example I have created a Java class named JavaReaderExample.java into which created an input stream using Reader and FileReader. To read the contents of file used the read() method of Reader class. Source Code JavaReaderExample.java import java.io.Reader; import java.io.FileReader; import java.io.IOException; public class JavaReaderExample { public static void main(String args[]) { Reader rdr = null; try { rdr = new FileReader("file.txt"); int c ; System.out.println(); System.out.println("***** OUTPUT *****"); System.out.println(); while((c= rdr.read()) != -1) { System.out.print((char) c); } System.out.println(); } catch(Exception ex) { System.out.println(ex); } finally { if(rdr != null) { try { rdr.close(); } catch(IOException ioe) { System.out.println(ioe); } } }// end finally }// end main }// end class Output When you will execute the above code you will get the output as follows : Advertisements Posted on: December Reader Post your Comment
http://roseindia.net/java/example/java/io/reader.shtml
CC-MAIN-2016-22
refinedweb
285
52.46
Strange error messages using ARM MDK Generic from Keiluserc_42198 Sep 21, 2014 4:20 AM Hi, I have followed the Cypress recommendation and installed the compiler from Keil. It builds my project successfully with a more compact code as the ARM GCC 4.7.3, but it generates in my main.c source some strange error messages. Example 1: uint32_t A1Tim; is marked with a red dot and the message: reference to uint32_t is ambiguous, #include <stdint.h> is specified Example 2: CyGlobalIntEnable; is marked with a yellow triangle and the message:implicit declaration of function is invalid in C99 Must I include special header files in order to avoid these error messages? Or install something else? Even if the project builds successfully, I don´t like error messages neither red nor yellow. Thanks for your hint and best regards Walter 1. Re: Strange error messages using ARM MDK Generic from KeilJoMe_264151 Sep 15, 2014 3:43 PM (in response to userc_42198) Different compilers may reqiure different libraries. Probably the definition for uint32_t occurs more than once and the declaration for CyGlobalIntEnable is missing. Since the cy_boot component (which contains the definition of CyGlobatIntEnable) is "automatically" included into every project -as the System Reference Guide says- it might be the case that you have to include that reference manually. Are there any recommendations for libraries coming with that compiler? Bob 2. Re: Strange error messages using ARM MDK Generic from Keiluserc_42198 Sep 16, 2014 3:59 AM (in response to userc_42198) Hi, Many thanks for your quick answer. For using the Keil compiler, I have installed uVision5 (32K version) and defined the path of the compiler in PSoc Creator. I have not seen any hint from Keil regarding the usage in the Cypress environment. In case, I comment the <stdint.h>, the error messages stay. In case, I comment the <project.h>, these errors diappear, but others came out. I think, I will give up the Keil stuff and go back to the good old GCC. Does somebody know, when the GCC 4.8 will be included in the creator? Best regards Walter 3. Re: Strange error messages using ARM MDK Generic from KeilMarkS_11 Sep 18, 2014 8:47 PM (in response to userc_42198) You definitely need the project.h file to be included. It makes sure you "see" the CyGlobalIntenable macro and the types header. Normally you can switch between the two compilers and simply rebuild. I cannot comment on the errors you see though. Maybe you could post them? I suspect there is an include path issue, which is why you get "not found" errors. The issue is not the compiler itself - you get the editor icons without even running the compiler. Take a look at your project settings and compare the include paths for the GCC and MDK compilers. Go to Project->Build Settings and use thew toolchain pull-down to switch between the compilers so you can see the includes (under). -- Mark. 4. Re: Strange error messages using ARM MDK Generic from Keiluserc_42198 Sep 20, 2014 5:15 AM (in response to userc_42198) Hi Mark, Many thanks for your hints. I have attached the error messages, which come up in the IDE, if ARM MDK is selected. It seems, it is a problem of the IDE, because the compiler builds successfully. Maybe uint32_t has been defined twice with different declaration. In the build settings of the project, I did not see any include settings for both compilers. best regards Walter - Error11.jpg 52.4 K 5. Re: Strange error messages using ARM MDK Generic from Keiluserc_42198 Sep 20, 2014 5:16 AM (in response to userc_42198) Next error. - Error21.jpg 50.3 K 6. Re: Strange error messages using ARM MDK Generic from KeilDaKn_263916 Sep 20, 2014 6:03 AM (in response to userc_42198) This might help - Regards, Dana. 7. Re: Strange error messages using ARM MDK Generic from Keiluserc_42198 Sep 21, 2014 4:20 AM (in response to userc_42198) Hi Dana, Many thanks for you interesting hint about systick. This function works well in my project, but the shown errors appear only if the Keil compiler is selected. Walter
https://community.cypress.com/thread/18435
CC-MAIN-2020-40
refinedweb
694
65.12
- NAME -) - cache_only => true | false (default: false) - max_includes => number (default: 30) - debug_dump => true | false (default: true) - encode_charset => charset (default: undef) - decode_charset => charset (default: undef) - TAL SYNTAX - METAL MACROS - EXPRESSIONS AND MODIFIERS - ADVANCED PETAL - Expression keywords - DECRYPTING WARNINGS AND ERRORS - EXPORTS - AUTHOR - SEE ALSO NAME Petal - Perl Template Attribute Language - TAL for Perl! => some_object() ); some_object() is a subroutine that returns some kind of object, may it be a scalar, object, array referebce or hash reference. Let's see what we can do... Version 1: WYSIWYG friendly prototype. 2: Object-oriented version Let's now say that my_var is actually an object with a method hello_world() that returns Hello World. To output the same result, your line, which was: <span tal:Hola, Mundo!</span> Would need to be... EXACTLY the same. Petal lets you access hashes and objects in an entirely transparent way and tries to automagically do The Right Thing for you. This high level of polymorphism means that in most cases you can maintain your code, swap hashes for objects, and not change a single line of your template code. Version 3: Personalizable Now let's say that your method hello_world() can take an optional argument so that $some_object- object 4: Internationalized Let's say that you have a directory called hello_world with =>,' - Alias for 'XHTML' 'XHTML' - Petal will use Petal::Parser to parse the template 'XML' - Petal will use Petal: module. memory_cache => true | false (default: true) If set to false, Petal will not use the Petal::Cache::Memory module. cache_only => true | false (default: false) If set to true, Petal will return true after having compiled a template into perl code and a subroutine , and optionally using disk_cache or memory_cache if either is set.. The location for this file is wherever File::Spec->tmpdir() specifies as a temp directory (usually /tmp on a unix system).. TAL SYNTAX This functionality is directly and shamelessly stolen from the excellent TAL specification:. define: repeat/index index returns the numeric position of this item within the loop, starts with one not zero. repeat/number number is an alias for index. repeat/even even is true if the position is even (0, 2, 4 ...) repeat/odd odd is true is the position is odd (1, 3, 5 ...) repeat/start start is true if this is the first item. repeat/end end is true if this is the last item. repeat/inner inner is true if this is not the start or end. keyword. and tal:replace are *NOT* aliases. The former will replace the contents of the tag, while the latter will replace the whole tag. Indeed you cannot use tal:content and tal:replace in the same tag. omit-tag Abstract <tag tal:Some contents</tag> Example <b tal:I may not be bold.</b> If not:bold is evaluated as TRUE, then the <b> tag will be omited. If not:bold TRAP: Don't forget that the default prefix is petal: NOT tal:, until you set the petal namespace in your HTML or XML document as follows: <html xmlns: METAL MACROS Petal supports an implementation of the METAL specification, which is a very WYSIWYG compatible way of doing template includes. define-macro In order to define a macro inside a file (i.e. a fragment to be included), you use the metal:define-macro directive. For example: File foo.xml ============ <html xmlns: <body> <p metal: (c) Me (r)(tm) (pouet pouet) </p> </body> </html> use-macro In order to use a previously defined macro, you use the metal:use-macro directive. For example: File bar.xml ============ <html xmlns: <body> ... plenty of content ... <p metal: Page Footer. </p> </body> </html> define-slot In any given macro you can define slots, which are bits of macros that can be overridden> fill-slot) < xmlns: keyword. keyword, i.e. fresh string:$foo/bar, ${baz/buz/blah} You can use fresh with structure if using by setting the PETAL_INPUT environment variable. You can set $Petal::OUTPUT using by setting the PETAL_OUTPUT environment variable. perl -MPetal -e code template.xml Displays the perl code for template.xml. You can set $Petal::INPUT using by setting the PETAL_INPUT environment variable. You can set $Petal::OUTPUT using by setting the PETAL_OUTPUT environment variable. perl -MPetal -e lcode template.xml Displays the perl code for template.xml, with line numbers. You can set $Petal::INPUT using by setting the PETAL_INPUT environment variable. You can set $Petal::OUTPUT using 9. (optional) Petal internationalizes the resulting output. If you are under a persistent environment a la mod_perl, subsequent calls to the same template will be reduced to step 8 until the source template changes... EXPORTS None. AUTHOR Authors: Jean-Michel Hiver,:
https://metacpan.org/pod/Petal
CC-MAIN-2015-11
refinedweb
776
65.62
Back to: Dot Net Design Patterns With Real-Time Examples Singleton VS Static Class in C# with Examples In this article, I am going to discuss the Singleton vs Static class in C# with examples. I strongly recommended you to read the Singleton class and Static class articles before proceeding to this article. As part of this article, we are going to discuss the following important pointers. - What are the similarities between Singleton and Static class in C#? - What are the differences between Singleton vs Static class in C#? - Memory Management of Static Class and Singleton Class in C#. - Realtime examples of Static class and Singleton class in C#. What are the similarities between Singleton and Static class in C#? Before discussing the differences between them, let’s first discuss the similarities between Singleton vs Static class in C# - Both static class and singleton class can have only one instance of a copy that is available in memory throughout the whole application. They both are used for holding the global state of an application. - Both static classes and singleton classes can be implemented as thread-safe. What are the differences between Singleton vs Static class in C#? The most important point that you need to keep in mind is that Static is a language feature whereas Singleton is a design pattern. So both belong to two different areas. With this keep in mind let’s discuss the differences between Singleton vs static class in C#. - We cannot create an instance of a static class in C#. But we can create a single instance of a singleton class and then can reuse that singleton instance. - When the compiler compiles the static class then internally it treats the static class as an abstract and sealed class. This is the reason why neither we create an instance nor extend a static class in C#. - The Singleton class constructor is always marked as private. This is the reason why we cannot create an instance from outside the singleton class. It provides either public static property or a public static method whose job is to create the singleton instance only once and then return that singleton instance each and every time when we called that public static property/method from outside the singleton class. - A Singleton class can be initialized lazily or can be loaded automatically by CLR (Common Language Runtime) when the program or namespace containing the Singleton class is loaded. whereas a static class is generally initialized when it is first loaded for the first time and it may lead to potential classloader issues. - It is not possible to pass the static class as a method parameter whereas we can pass the singleton instance as a method parameter in C#. - In C#, it is possible to implement interfaces, inherit from other classes and allow inheritance with Singleton class. These are not possible with a static class. So the Singleton class is more flexible as compared to static classes. - We can clone the Singleton class object whereas it is not possible to clone a static class. It is possible to dispose of the objects of a singleton class whereas it is not possible to dispose of a static class. - We cannot implement the Dependency Injection design pattern using Static class because the static class is not interface driven. - Singleton means a single object across the application lifecycle, so the scope is at the application level. As we know the static class does not have any Object pointer, so the scope is at the App Domain level. Memory Management of Static Class vs Singleton Class in C#: There is a little confusion about the memory management of static vs Singleton class in C#. The most important point that you need to remember is any class whether it is declared itself as static or any member of if it is declared as static then that class or those static members would not be collected by Garbage Collector. The Static variables or static classes are not stored in the Stack memory. There is some specific space in Heap memory called High-Frequency Heap where the static classes and static variables are stored. This space is beyond the scope of Garbage Collector and hence, the memory gets released only when the corresponding Process or AppDomain gets unload. As the singleton class holds a static reference, so it cannot be collected by the Garbage Collector (GC) and both (Static and Singleton class) get destroyed only when the corresponding Process or AppDomain gets unloads. The Static class example in C# – Temperature Converter Here is an example of a static class that contains two methods that convert temperature from Celsius to Fahrenheit and from Fahrenheit to Celsius. We are pretty sure that the formulas for converting temperature from Celsius to Fahrenheit and from Fahrenheit to Celsius will not change at all and hence we can use static classes with static methods which do the conversion for us as shown below. Program {; } Console.WriteLine("Press any key to exit."); Console.ReadKey(); } } Run the application and see the output: Real-world Examples of Singleton Class: Some of the real-world scenarios where you can use the singleton design pattern are as follows - Managing Service Proxies - Managing Database Connections - Logging - Caching - Data Sharing - Application Configuration Management In the next article, I am going to discuss one real-time example of the singleton design pattern using ASP.NET MVC application. Here, in this article, I try to explain Singleton VS Static Class in C# step by step with a simple example. I hope this article will help you with your needs. 2 thoughts on “Singleton VS Static class in C#” Now I understood the difference between singleton vs static class in C#. Thank you for this article. Its simple and easy understand. 3. The Singleton class constructor is always marked as private. 6. In C#, it is possible to implement interfaces, inherit from other classes and allow inheritance with Singleton class. How can you inherit from a singleton class if the constructor is “always marked as private”? Think about that.
https://dotnettutorials.net/lesson/singleton-vs-static-class/
CC-MAIN-2020-05
refinedweb
1,015
52.29
C API: Callbacks for UReplaceable. More... #include "unicode/utypes.h" Go to the source code of this file. C API: Callbacks for UReplaceable. Definition in file urep.h. An opaque replaceable text object. This will be manipulated only through the caller-supplied UReplaceableFunctor struct. Related to the C++ class Replaceable. This is currently only used in the Transliterator C API, see utrans.h . Definition at line 44 of file urep.h. A set of function pointers that transliterators use to manipulate a UReplaceable. The caller should supply the required functions to manipulate their text appropriately. Related to the C++ class Replaceable.
http://icu-project.org/apiref/icu4c/urep_8h.html
CC-MAIN-2018-30
refinedweb
101
55
Imports are an inevitable part of Python and Django development. Pep8, which is the official style guide for Python, recommends imports be placed at the top of the file, on separate lines, and grouped in the following order: - Standard library imports - Related third party imports - Local application/library specific imports Whenever possible, be as explicit as possible with imports. Here's an example views.py file from the Blog app built in my Django for Beginners book. # blog/views.py from django.views.generic import ListView, DetailView from django.views.generic.edit import CreateView, UpdateView, DeleteView from django.urls import reverse_lazy from .models import Post # explicit relative import class BlogListView(ListView): model = Post template_name = 'home.html' The top 3 lines are absolute imports which are used when importing packages from outside a given app. This is how all Django core code is imported. The database model is imported using an explicit relative import--we didn't hardcode the app name in here which makes it much more reusable. If we had instead done from blog.models import Post then if the name of the blog app changed in the future or we wanted to separate out this code, the import would fail. Another good rule of thumb is to never use * which accesses all imports. For example, this is a bad idea: # blog/views.py from django.views.generic import * # BAD IDEA! Why import things you don't need? Plus what if views.generic changes at some point in the future in unforeseen ways which opens up security concerns. Takeaway You'll likely see different import styles in open source and professional code settings. Try to follow PEP8 as closely as possible. Use absolute imports when necessary and prefer explicit relative imports for your local Django code. Discussion
https://dev.to/wsvincent/django-best-practices-imports-24p7
CC-MAIN-2021-04
refinedweb
298
59.8
As a simple example of an extension lets add a new menu item in the Tools menu which simply pops-up an alert window that says "hello world". The Wizard creates some XUL and code that does something similar but not in the simplest way so let's create our own layout and code. First open the file firefoxOverlay.js in NotePad and change it to read: <?xml version="1.0" encoding="UTF-8"?><!DOCTYPE overlay SYSTEM "chrome://helloworld/locale/ helloworld.dtd"><overlay id="helloworld-overlay" xmlns=" gatekeeper/there.is.only.xul"> These three lines always start an XUL file and simply establish its type and namespace. The third line specifies the id of your overlay. There are additional "header" lines you can include in the XUL file but these are the most important. Next we can specify a file that contains JavaScript to be run when the overlay is installed. In our case this is just the overlay.js file that the Wizard created: <script src="/overlay.js"/> Now we can add lines that look a lot like HTML and define menu items, buttons, textboxes and so on. These will be added to the browser's user interface but first we have to say exactly where our new controls will be added. As already mentioned, the entire browser user interface, including any HTML pages it might be displaying forms a single huge DOM tree and all we have to do is specify the id of the node to which we want to attach our controls. The only problem is how to discover the id of the existing control? You might think that the answer was to look it up in the documentation but in practice it is usually easier to use the DOM Inspector, which is explained later. The Tools menu has the id "menu_ToolsPopup" and this is where our overlay starts: <menupopup id="menu_ToolsPopup"> <menuitem id="helloworld-hello" label="Helloworld" oncommand= "helloworld.onMenuItemCommand();"/> </menupopup></overlay> The new menu item has the id "helloworld-hello" and it is important that it uses a unique id to avoid conflicts within the DOM. You can add additional attributes to determine the behaviour and look of the new menu item. Setting the oncommand attribute determines the name of the function called when the user clicks the menu option. In this case it's the onMenuItem method of the helloworld object, both of which are defined in the companion JavaScript file. That's all there is to creating the XUL file for the overlay. To add or modify other elements of the user interface all you need to do is lookup the XUL element at: The next step is to write the JavaScript we need. Open the Overlay.js file in Notepad and change it to read as follows: var helloworld = { onLoad: function() { // initialization code this.initialized = true; }, onMenuItemCommand: function() { alert("Hello World"); },};window.addEventListener("load", function(e) { helloworld.onLoad(e); }, false); As long as you know a little JavaScript this should make sense. The first part creates a JavaScript object with two methods, onLoad and onMenuItemCommand. The onLoad function simply sets a local variable initialised to true so the other methods can check that it has been initialised and everything is loaded and ready to go. The onMenuItemCommand simply pops up an alert box with the message in it. Notice that this method has already been linked to the menu item event in the XUL file. The onLoad method, however, still needs to be linked to a suitable event. This is the job of the final line which adds the onLoad method to the list of methods that are called when the browser's "load" event fires.
http://www.i-programmer.info/projects/36-web/171-extending-firefox-and-thunderbird.html?start=2
CC-MAIN-2017-34
refinedweb
615
71.75
Acutally, I don't understand how it works since you approaches a memory which is not yours to access. Like people told you before size is not the element indicator because we start from 0. Printable View Acutally, I don't understand how it works since you approaches a memory which is not yours to access. Like people told you before size is not the element indicator because we start from 0. I changed it completely I put a while loop in instead I think the code is ok now cheers. sorry walla I don't understand what you mean. What is your current code? Ok it's probably still wrong ha.. works fine though. Code: using namespace std; string mirrorends(string s) { int size = s.size(); string mirror; int i = 0; while (s[i]==s[size -(i+1)]) { mirror = mirror + s[i]; i++; } return mirror; } int main(int argc, char *argv[]) { string a = mirrorends("racecar"); cout << a << endl; system("PAUSE"); return EXIT_SUCCESS; } why not use iterators? std::string provides forward and reverse iterators, accessible with begin/end and rbegin/rend. you could start a for loop, initializing two iterators with begin and rbegin, and increment both each time through the loop. as long as the values referred to by the iterators are the same, you continue the loop and add the current value of the iterator you received from begin to the end of your string. >> Ok it's probably still wrong ha.. works fine though. Works fine for which inputs? I liked your for loop better, honestly. The bug you had was really simple. Did you figure out what it was or did you just want to try the while loop? Note that your while loop actually has the same type of problem as your for loop did (you have to know when to stop). >> why not use iterators? For something this simple that is a learning exercise it's probably not necessary, especially since it's unlikely that caffrea4 has been introduced to them. Also note that he or she would have to solve the same problem for your pseudocode as in the for and while loops, so it wouldn't be any more correct than what is there already.
http://cboard.cprogramming.com/cplusplus-programming/143270-string-problem-2-print.html
CC-MAIN-2014-52
refinedweb
373
73.47
RationalWiki:Saloon bar/Archive5 Contents - 1 Help! - 2 Calling all Japanese, or part-Japanese Users on RW (日本人の皆様へ)) - 3 Bush Video - 4 Spoof names - 5 Reverting multiple changes at once - 6 RWW problem - 7 Toby Keith - 8 Phew - 9 RW technical support - 10 Halp! - 11 This video.... wow. - 12 Google - 13 Real name - 14 King David - 15 Introspective - 16 A quick update - 17 Copyright - 18 Where is Your God, Now, Kurt Warner?!?!?! - 19 Bambi's Mom - 20 Is it possible to hide IPs? - 21 Sidebar - 22 Can we have lurkers come out day? - 23 Troubling... - 24 Metapedia - 25 Anything new 'round here? - 26 Hitler and religion - 27 Darwin Paper - 28 Breaking news... - 29 Policy link on Special:BlockIP - 30 Where we are now - 31 Goat arrested in Nigeria - 32 Modified Quote Generator - 33 New Meta-category(gories?) - 34 Some stuff I found on MediaWiki - 35 Work in progress - 36 Night Mode!?!?! Help![edit] Why can't I use the intercom? I have tried sending it to all the groups and it still gives me a permission error. Evil word Phantom Hoover! 15:16, 30 January 2009 (EST) - It works for me on general site news. Could it be your image sig? ГенгисIs the Pope a Catholic? 15:25, 30 January 2009 (EST) - No, it worked with the HTML sig, and the intercom doesn't use your sig anyway. Evil word Phantom Hoover! 15:30, 30 January 2009 (EST) - Your first point doesn't make any sense (it worked with the HTML sig?) but I do realise that the actual sig is not used in the intercom. Have you tried it with another account? ГенгисIs the Pope a Catholic? 15:49, 30 January 2009 (EST) - When my sig was some HTML, the intercom still didn't work. Evil word Phantom Hoover! 16:06, 30 January 2009 (EST) - What browser are you using? tmtoulouse 16:08, 30 January 2009 (EST) - Safari 3.2.1. I'll try it in Firefox 3. Evil word Phantom Hoover! 16:12, 30 January 2009 (EST) - Yes, it works. Explain. Evil word Phantom Hoover! 16:14, 30 January 2009 (EST) - BTW your sig expands the line spacing considerably. ГенгисIs the Pope a Catholic? 16:19, 30 January 2009 (EST) - I am aware of that; I should ask Nx to sort that out at some point. Evil word Phantom Hoover! 16:21, 30 January 2009 (EST) - The issue is that the Safari toolbox passes variables in a weird format, the same problem occurs in the new google Chrome as well. I will need to figure out what it is doing and do some preprocessing before the authentication setup to get it to work. tmtoulouse 16:32, 30 January 2009 (EST) - I cannot use the intercom either, what's going on?-- Redcoat 06:35, 31 January 2009 (EST) - Try sending to general site news, then try with Firefox. Evil word Phantom Hoover! 06:37, 31 January 2009 (EST) - Nope, I just get a permission error.-- Redcoat 06:40, 31 January 2009 (EST) - In that case, try using Firefox. Evil word Phantom Hoover! 06:44, 31 January 2009 (EST) - That doesn't work either-- Redcoat 07:50, 31 January 2009 (EST) - Make sure you are actually using Firefox, and try sending to general sit news. 92.235.204.231 08:16, 31 January 2009 (EST) - Beaten by a BoN. Evil word Phantom Hoover! 08:18, 31 January 2009 (EST) - Or am I!!! (BTW it still isn't working!)-- Redcoat 13:25, 31 January 2009 (EST) - It doesn't work on anything other than Firefox. Evil word Phantom Hoover! 13:41, 31 January 2009 (EST) Are you a member of the group you are attempting to send a message out on Red? tmtoulouse 13:48, 31 January 2009 (EST) Calling all Japanese, or part-Japanese Users on RW (日本人の皆様へ))[edit] このウエブサイトで日本国憲法に詳しい人いませんか? もしいるならば是非憲法に関してお書き下さいよろしくお願い致します!-- Redcoat 20:05, 30 January 2009 (EST) - My hovercraft is full of eels? - My nipples explode with delight? - Ok, babelfish tells me it's something to do with the Japanese constitution. care to expand on that? --PsyGremlinWhut? 07:42, 31 January 2009 (EST) - It's probably a tirade against Article 9; see his userpage. Evil word Phantom Hoover! 08:18, 31 January 2009 (EST) Addendum: The contents of this message shall remain secret until someone finds a decent translation program (not a cheap chinese imitation)-- Redcoat 13:15, 31 January 2009 (EST) - Google translate (not cheap chinese imitation). Others are welcome to suggest a better translation. Hiding or obscuring information or the process of how to get it seems to run counter to some ideals here. --Shagie 01:04, 6 February 2009 (EST) Bush Video[edit] Just found this via a WIGO:World item. Thought it was quite well done. ГенгисIs the Pope a Catholic? 20:06, 30 January 2009 (EST) - I certainly got a few lulz from it, you're quite right in saying it was well done. I chuckled rather heartily when he came out with "they need to be eatin' US beef". -Redbacknot Redneck 09:21, 31 January 2009 (EST) Spoof names[edit] I demand that the person who created those spoof names last night confess. Evil word Phantom Hoover! 08:47, 31 January 2009 (EST) - I assumed it was you playing around with things. Radioactive afikomen Please ignore all my awful pre-2014 comments. 21:23, 31 January 2009 (EST) - Since it wasn't you, I'm inclined to think it's CUR. He recently made a spoof of my name, so it would fit a pattern. Radioactive afikomen Please ignore all my awful pre-2014 comments. 21:23, 31 January 2009 (EST) - It wasn't me who made Evitcaoidar Nemokifa. Really. But give me a second. . . Watch the user creation log. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 10:29, 1 February 2009 (EST) - Look at nemokifa evitcaoidaR's rights log. Evil word Phantom Hoover! 12:20, 1 February 2009 (EST) Reverting multiple changes at once[edit] I noticed during the recent silliness over at the Poe's Law article that there were several changes made rather quickly. I did a bit of fiddling and discovered how to revert more than one edit at a time (I think), but by the time I'd figured it out, the article was already being cleaned up. Perhaps we should add a quick note somewhere explaining how to revert back more than just the latest change without having to do it one-by-one, maybe in the How to handle vandalism article or the sysop guide, just to make it a bit easier to those (like myself) who are a bit slow figuring it out for themselves. Just for clarification, because I never had the opportunity to test it, here's how I think it works. Open the Fossil Record, compare the latest edit to the latest proper (pre-wandalism) version, then click undo on the diff page... right? -Redbacknot Redneck 09:04, 31 January 2009 (EST) - No; if you look, I tried undo; the best way is to click the "edit" tab on the last good version and click "save". Evil word Phantom Hoover! 09:08, 31 January 2009 (EST) - I didn't realize you could do that, This person's knowledge is growing rapidly!, thanks. -Redbacknot Redneck 09:09, 31 January 2009 (EST) - Still, should we put that method somewhere, other than here of course, just so newbies (and people who come up with over-elaborate and incorrect methods) know how it's done? -Redbacknot Redneck 09:15, 31 January 2009 (EST) - I think so too - we shouldn't assume new editors here are familiar with wikis. Yours trulyDear Sir 09:19, 31 January 2009 (EST) RWW problem[edit] Why am I getting this when I google rationalwikiwiki? Yours trulyDear Sir 10:04, 31 January 2009 (EST) - I think Google may have a slight problem, I get that on all searches right now. Even "fluffy kittens". --AKjeldsenCum dissensie 10:07, 31 January 2009 (EST) - They're even calling google.com a harmful site. Besides, AKjeldsen, were you not aware that fluffy kittens are the most dangerous kittens of all? They look cuddly, but have such sharp little claws. -Redbacknot Redneck 10:09, 31 January 2009 (EST) - And what about tiger kittens? Yours trulyDear Sir 10:15, 31 January 2009 (EST) I see what's causing it now - bad karma. Yours trulyDear Sir 10:21, 31 January 2009 (EST) - Seems to be fixed now. Too bad - I thought of getting a screenshot of "Conservapedia: This site may harm your computer" but only too late. --AKjeldsenCum dissensie 10:26, 31 January 2009 (EST) - Well, WOT (Web of Trust), a Firefox extension designed to warn users about dangerous sites, still pops up a big "Warning!" when CP loads, so that'll have to do until Google's next brainfart. As for the tiger kittens, INH, I dunno about you, but I'd be sorta disinclined to hug them hence reducing the threat of getting kitty-swiped... or eaten. -Redbacknot Redneck 10:58, 31 January 2009 (EST) - Insert name here: +30,000 points for the edit comment:) Z3rotalk 10:27, 31 January 2009 (EST) Toby Keith[edit] So I noticed that one of the saloon bar quotes, about "beer for my horses" is from a Toby Keith song about how great capital punishment is. May I direct attention to this verse: -. - (From here. Some punctuation added by me.) So, right. I'd advocate finding better quotations or lyrics. Also, from a style standpoint, I have a hard time liking a song that uses the word "pappy." It just grates on me. CorryI think hallucinations are a side effect of Teamocil. 14:32, 31 January 2009 (EST) - I'd never heard of it before, but having just listened to about half of the song on YouTube, I agree it's awful. It's also kindof put me off Willie Nelson. I thought he was a bit more left-leaning than to involve himself with a song like that. ŴêâŝêîôîďMethinks it is a Weasel 14:38, 1 February 2009 (EST) - I've removed it from the template. ŴêâŝêîôîďMethinks it is a Weasel 13:48, 4 February 2009 (EST) Phew[edit] I've moved all the Help files to Category "Help". If I've missed any or cocked up any linkage then I apologise. (Toast) and marmalade 21:01, 31 January 2009 (EST) RW technical support[edit] So here is my problem. Issues with extensions, the server, and what not crop up from time to time. They get talked about on anywhere from a close to a dozen different pages. I need a single place to find all the problems. I would like to set up something like RationalWiki:Technical support and have issues listed there in one place for me to find. Also it could be a place for anyone who adds stuff to the site such as various java scripts to offer support and maybe a few problems can simply be addressed by general users. Any intrepid users care to get this going? tmtoulouse 21:19, 31 January 2009 (EST) - How's that? (I'll put a note on the chalkboard) (Toast) and marmalade 21:56, 31 January 2009 (EST) - Ironically (considering the above section), shouldn't that be a "kelp" page? PS, I think we should move all the "help" namespace to "kelp". But, of course, I'm wrong. Giant algae rule! ħuman 22:33, 31 January 2009 (EST) - By the way IF YOU LOGGED ON RATHER THAN IP'ING then your user talk page would work pretty well. No? (Toast) and marmalade 12:28, 1 February 2009 (EST) - Well, God forbid Tmtoulouse logs on to his same account every day. What would he do without his multiple IPs and socks? Radioactive afikomen Please ignore all my awful pre-2014 comments. 23:13, 1 February 2009 (EST) Halp![edit] I recently stumbled across an external link on a talk page somewhere here which led to a reasonable article, but when I went to the home page it turned out to be a bastion of complete batshit craziness (complete with the overuse of awful graphics). And now I can't find it anymore! I ask because I came across a great candidate for Article of the Weak there, and I would really appreciate it if someone helped me find it again. Radioactive afikomen Please ignore all my awful pre-2014 comments. 22:24, 31 January 2009 (EST) - Can you look at your browser's history and find it that way? ħuman 22:42, 31 January 2009 (EST) - I tried that. I couldn't find it. Radioactive afikomen Please ignore all my awful pre-2014 comments. 22:47, 31 January 2009 (EST) - OK, I'll check mine, then. ħuman 22:49, 31 January 2009 (EST) - If his History's anything like mine, it'd be easier to find a piece of hay in a needlestack. Toast 22:51, 31 January 2009 (EST) - Which unfortunately that's exactly what it's like. Radioactive afikomen Please ignore all my awful pre-2014 comments. 23:12, 31 January 2009 (EST) - 700 edits to RW, aw, there's got to be something in here! ħuman 23:29, 31 January 2009 (EST) - I made something like 300 edits yesterday alone—would you be able to fish through that? Radioactive afikomen Please ignore all my awful pre-2014 comments. 00:01, 1 February 2009 (EST) - Copy, paste, delete, look at what is left? And sorry about exaggerating your edit count ;) ħuman 00:07, 1 February 2009 (EST) - It's not that TimeCube thing is it? ГенгисIs the Pope a Catholic? 11:19, 1 February 2009 (EST) - Ah, I found it—here it is! Thank you to everyone who thought it worth commenting on this thread. Radioactive afikomen Please ignore all my awful pre-2014 comments. 23:05, 1 February 2009 (EST) This video.... wow.[edit] I just finished watching this video on youtube, and I must admit that it is a very insightful and well-made one, and I sincerly think that we, in the Wiki of Rationality might enjoy seeing it. Cheers. Javasca₧ no hell below him - It's not as good as his other videos though. My favourite is Evolution is a blind watchmaker -- Nx talk 12:00, 1 February 2009 (EST) Google[edit] Have you guys heard about google breaking earlier today or something?-- Redcoat 14:31, 1 February 2009 (EST) - Have you read the above posts? Evil word Phantom Hoover! 14:32, 1 February 2009 (EST) - maybe he just skimmed the titles - it's under "RWW problem". Yours trulyDear Sir 14:35, 1 February 2009 (EST) - I admit , I skimmed the titles :c -- Redcoat 14:40, 1 February 2009 (EST) - A bracket is more standard. Evil word Phantom Hoover! 14:43, 1 February 2009 (EST) - Oh go stuff yourself-- Redcoat 14:45, 1 February 2009 (EST) - I am getting really close to desysopping you. Evil word Phantom Hoover! 14:47, 1 February 2009 (EST) - No fair--I didn't get to de-sysop CUR!!! TheoryOfPractice 15:05, 1 February 2009 (EST) - CUR didn't use this many ad homs. Evil word Phantom Hoover! 15:14, 1 February 2009 (EST) - CUR was (I stress was) being an effing pain to everyone, though. (Toast) and marmalade 15:25, 1 February 2009 (EST) - He didn't redirect "Idiot" to someone else. He was an effing pain, but he was civil. Evil word Phantom Hoover! 15:48, 1 February 2009 (EST) - Being civil is not a requirement to be a sysop. --AKjeldsenCum dissensie 15:50, 1 February 2009 (EST) - (EC)I would like to point out that on any website where people are not allowed to poke good-natured fun at the leaders of the site, something is wrong there. Very wrong. Phantom Hoover, it was Redcoat's idea of a joke. Live with it. I deal with worse every single day here, or at least I used to. I suggest that, if it annoys you, you edit war on it, redirecting it to ASchlafly, Redcoat himself, or EdPoor. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 15:52, 1 February 2009 (EST) - But it wasn't good-natured fun. It was an insult, and not an insult made in frustration or a funny insult, it was just calling me an idiot. It was an empty threat anyway, but I am getting fed up with him. Evil word Phantom Hoover! 15:55, 1 February 2009 (EST) - According to Redcoat, it was. Just because you are sour about it doesn't mean that he should be desysopped, especially since much bigger things have been done by sysops in the past. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 16:01, 1 February 2009 (EST) - I know, I was getting annoyed with him. Evil word Phantom Hoover! 16:03, 1 February 2009 (EST) (unindent)(EC)Edit warring annoys me, though. I suggest that if it annoys you, CUR, then go and do something that doesn't annoy you. Yours trulyDear Sir 15:58, 1 February 2009 (EST) - Hey, Phantom! Remember this? Pot, I name thee charcoal coloured; signed kettle. (Toast) and marmalade 07:44, 2 February 2009 (EST) Real name[edit] When does the "real name" field in your preferences come up? Evil word Phantom Hoover! 15:47, 1 February 2009 (EST) - The "user profile" tag, box 1. Yours trulyDear Sir 15:51, 1 February 2009 (EST) - I meant when did it show up elsewhere. Evil word Phantom Hoover! 15:52, 1 February 2009 (EST) - Sorry. Yours trulyDear Sir 15:59, 1 February 2009 (EST) When does the "real name" field in your preferences come up? Evil word Phantom Hoover! 15:47, 1 February 2009 (EST) - It allows Trent to track you down and steal your organs when he needs money for beerserver maintenance. Otherwise, I don't think it does anything. Oh, and I think there's something hypothetical about attribution if the wiki ever gets published, but that's not particularly relevant here. --AKjeldsenCum dissensie 15:53, 1 February 2009 (EST) - You mean I typed "enaruM .A bocaJ" into my preferences for nothing? 9K ruoy ot eornoC eht AR 11:32, 2 February 2009 (EST) King David[edit] I do hope that it's been quiet here because UK RationalWikians have been watching David Attenborough's Charles Darwin and the Tree of Life. ГенгисIs the Pope a Catholic? 16:58, 1 February 2009 (EST) - Oh BUGGER!!!!!!!!!!!!!!!! Yours trulyDear Sir 17:03, 1 February 2009 (EST) Introspective[edit] We seem to be doing mostly navel gazing lately. What with new guidelines and article moves. Is ther nothing happening out there? (Toast) and marmalade - I think we are trying to figure out what we always needed to figure out - What are we, if all we are is anti-Conservapedia? We share this with Republicans for what is it to be Republican today, if all it means is to be anti_Democrat? I have to admit I'm getting bored of developing RW, but I still enjoy the people here and it still makes me smile. I still think Andy shouldn't be teaching kids. And I still think that Conservapedia calling itself "The Trustworthy Encyclopedia" should be a contravention of the Trades Description Act. That is all. DogP 18:57, 1 February 2009 (EST) - I've got kindof bored of CP lately, & have enjoyed the other stuff going on at RW, albeit the community standards revamp is dragging on a bit & it will be nice to get it out of the way. It's good to broaden the site's horizons & not just be an anti-CP site. The Saloon bar was a definitely a good move, as RW socialising doesn't have to revolve agound wigo talk anymore. ŴêâŝêîôîďMethinks it is a Weasel 20:13, 1 February 2009 (EST) A quick update[edit] For those who don't care about American Football, I'm sticking you with some updates anyway. At halftime of the Superbowl, Steelers lead the Cardinals 17-7 at halftime, and proving that the PTC and crazy censorship groups still instill fear in the media, Bruce Springsteen is the halftime performer..... As such, since the Janet Jackson incident, the halftime shows have been Paul McCartney, The Rolling Stones, Prince, Tom Petty and the Heartbreakers and now The Boss.... So much for that whole "destroying culture and not caring about what anybody thinks" line of argument huh? SirChuckBFurther bulletins as events warrant 20:05, 1 February 2009 (EST) - What's a "Superbowl"? (Toast) and marmalade 20:23, 1 February 2009 (EST) - It's like a regular bowl, but more super. SirChuckBFurther bulletins as events warrant 20:34, 1 February 2009 (EST) - Aah ... with porridge? (Toast) and marmalade 20:44, 1 February 2009 (EST) - No, Ice Cream. Javasca₧ no hell below him - Yummy, I see why there's all the excitement. (Toast) and marmalade 21:21, 1 February 2009 (EST) - Yup, it looks like steel flavoured ice cream tonight. Just for the record. Javasca₧ no hell below him - Yes, the Cards almost took it, but they got pwned. And the Boss ruled, if nothing else by obviously not lip-synching. ħuman 23:04, 1 February 2009 (EST) - Stupid Cardinals. Can't even hold onto a lead. Last time I bet on you. Z3rotalk 23:07, 1 February 2009 (EST) FYI: a "superbowl" is like regular owl, only it is much better. Superb, in fact. DickTurpis 00:10, 2 February 2009 (EST) If someone takes a photo on my camera, who owns the copyright? (Toast) and marmalade 21:40, 1 February 2009 (EST) I guess it's in public domain, unless that person specifically copyrights it. You're probably good. The EmperorKneel before Zod! 21:44, 1 February 2009 (EST) Also, you could just keep quiet about it, there's a 99% chance nobody'll know. The EmperorKneel before Zod! 21:46, 1 February 2009 (EST) - It was hypith ... hiperth .. hypathetik ... imaginary acshually. (Toast) and marmalade 21:48, 1 February 2009 (EST) - By default, the person taking the picture owns the copyright. --AKjeldsenCum dissensie 21:50, 1 February 2009 (EST) - Aah, but what happens if I won't let her have it? can I wipe it with impunity? (Also hypowhatsit) (Toast) and marmalade 21:54, 1 February 2009 (EST) - Good question. I'd assume not, provided you allowed her to use the camera in the first place. However, if she deviously used the camera without permission, you might have a better case. --AKjeldsenCum dissensie 22:01, 1 February 2009 (EST) - Accomplished, or recognized, amateur photogs and their friends are an ugly "ownership" issue. Been there and done that. They think if they buy the film and pay for the processing (20th century crap), they own the pix. Of course, the photog thinks of them as "their" creation. Best to discuss first - very clearly. I'd say, give your friend their piccy, unless it is compromising ;) in which case, your disk crashed and you're very sorry. ħuman 23:15, 1 February 2009 (EST) - It is only a thought experiment - a dispute hasn't occurred - just struck me while I was uploading someone else's photo on my camera. (Toast) and marmalade 23:22, 1 February 2009 (EST) - Crude version: whoever pressed the button owns the copyright. Soft version: Most casual pix should probably just be PD, for simplicity. Complicated version: If someone uses your camera to create "art", they own it. If you don't have a pre-existing contract to share the royalties (hahahahahahaah), they belong to the snapper. PS, IANAL. ħuman 00:12, 2 February 2009 (EST) - The person who took the picture owns the copyright. However, that right is worthless if someone else owns the medium on which it was created, they then have the right to destroy it. If you asked them to take the picture then the work was commissioned and copyright does not transfer to you until payment is finalised. If there was no expectation of payment then you de facto own the copyright. That's my non-legally binding opinion. Owning the copyright does not give you the right to do what you want with the image. The status of the image can be affected by where the picture was taken, public or private property and you my need model-release approval. If someone takes an image with your camera they may have some difficulty in actually proving that they own the copyright. ГенгисIs the Pope a Catholic? 01:40, 2 February 2009 (EST) - It's exactly that simple, yes. In other words, when playing these games, download awful boilerplate contracts and make your personal relationships suck in order to make them conform to the Law. ħuman 02:01, 2 February 2009 (EST) - Generally, copyright issues only matter when there's money involved. Mixing money and friendship can be a recipe for disaster. It's like offering to pay your sister-in-law for cooking a nice lunch. ГенгисIs the Pope a Catholic? 03:52, 2 February 2009 (EST) - Welll there's also the (20th century) issue of "who owns the negatives. Usually the friend who pays for the film and developing thinks they do. IE, their buddy, the photog, simply did a favor for no pay and, usually, no recognition. I have run through this a few times, one with someone for whom I taking "album cover" type pix - ie, someday money might be involved. Oh, but, no, you're just my friend, you "did me a favor"... WTF? No, I worked for you for no pay and no credit. Yup, when the potential of money is involved, it changes everything. (PS, if those images ever turn up, I will sue her ;)) ħuman 00:01, 3 February 2009 (EST) Where is Your God, Now, Kurt Warner?!?!?![edit] Huh, Kurt? Guess God isn't a Cardinals fan after all, Warner. TheoryOfPractice 23:29, 1 February 2009 (EST) - God was backing Ben Roethlisberger. - User Failed to parse (PNG conversion failed; check for correct installation of latex and dvipng (or dvips + gs + convert)): \scriptstyle-i\ln(-1) 23:34, 1 February 2009 (EST) - I guess god helps those who help themselves (lazy god). Z3rotalk 23:36, 1 February 2009 (EST) - Everyone knows that God is a big Steelers fan. SirChuckBFurther bulletins as events warrant 23:58, 1 February 2009 (EST) - Hey! Jesus kept the Cardinals within the spread, so I made my 10 bucks, and that's all that matters. Way to go Jesus! DickTurpis 00:07, 2 February 2009 (EST) - @DT, glad it worked out for someone. Myself, I thought it was a well-contested game, and so, entertaining. Despite the fist-fights. And Bruce rocked. ħuman 00:20, 2 February 2009 (EST) - One guy I was watching it with had five buck on the first TD being a rushing touchdown by Roethlisberger at 13-1. He was pissed. - User Failed to parse (PNG conversion failed; check for correct installation of latex and dvipng (or dvips + gs + convert)): \scriptstyle-i\ln(-1) 00:23, 2 February 2009 (EST) - Human, obviously you haven't been keeping up. Bruce is an overweight liberal has-been. TheoryOfPractice 00:26, 2 February 2009 (EST) - Oh, yeah, I missed that. ħuman 00:39, 2 February 2009 (EST) - It took me five lines to realize that this wasn't about the Vatican, but some arcane American sport... l'arronsicut fur in nocte 08:07, 2 February 2009 (EST) - What sort of sport is it? Anything like cribbage? (Toast) and marmalade 08:20, 2 February 2009 (EST) - It might be their version of rugby. Evil word Phantom Hoover! 14:47, 2 February 2009 (EST) Bambi's Mom[edit] Evidently Google has been excoriated for having a picture of van hitting a deer on their Google maps street-view for somehwere near Rush, New York. It's now been removed, anyone here seen it? ГенгисIs the Pope a Catholic? 07:40, 2 February 2009 (EST) - Further up this page, somebody linked to this article, which shows a couple of the pics. ŴêâŝêîôîďMethinks it is a Weasel 08:46, 2 February 2009 (EST) Is it possible to hide IPs?[edit] Given the latest activity by TK taking action against IPs of users here (in disregard of their own 'standards') is it possible to make the mediawiki coftware stop reporting IPs of users not logged in? Is it something we should even consider? StarFish 07:52, 2 February 2009 (EST) - I doubt it's possible. As long as we allow editing by unregistered users (which I think we probably want to continue to do) the IP address will show up. ŴêâŝêîôîďMethinks it is a Weasel 08:41, 2 February 2009 (EST) - It's the reason why we request that people sign in. How would we know if Jinx was back if we hid IPs. ГенгисIs the Pope a Catholic? 09:18, 2 February 2009 (EST) - Hide revisions can hide the username but not the revision or comment. Evil word Phantom Hoover! 11:17, 2 February 2009 (EST) - The question really is "what do unlogged in users show up as"? One approach would be to have the md5 sum (or other one way function - crypt of the ip addresses in hex form?) be used as the account name. The question then becomes "how do we know if anyone is impersonating tmt when he isn't signed on?) I do believe it is possible to do with a one way hash function and that should foil TK. For example, I could be 0xb18a6bc87ab61eb215f14cf668e6e60c or rwqCj5RXXgL2s (the 'rw' is the salt for crypt of the hex representation of my ipaddress (8 characters - perfect for crypt())). If tmt wanted though, he could even remove the salt afterwards making it that much harder for someone with moderate coding skill to figure out. Using a hidden salt known only to me (as the programmer doing the hash), my IP could be named kFCxB0TEif2. Not knowing the salt (but using it) drastically increases the search space. The advantage of using crypt is the short name - md5sum is even better (and you could stick a huge salt in there making it impossible (sans a phd in math and computing power measured in acres) for anyone to reverse. Though, one could convert the md5sum back to bytes and pack it with uuencode to make a short name again. Hmm... print pack("u",join('', map { chr(hex($_)) } split(/(..)/,'b18a6bc87ab61eb215f14cf668e6e60c'))); @`+$`B@!K`,@`>@"V`!X`L@`5`/$`3`#V`&@`Y@#F``P` - Ok, scratch uuencoding it. Thats not even vaguely pronounceable line noise. Still, the idea remains of one way hashes to obscure the ip address.--Shagie 22:59, 2 February 2009 (EST) - Hey, Shagie: we're generally English speaking on this wiki. Any chance of a translation? (Toast) and marmalade 08:56, 3 February 2009 (EST) - Hey, I know a one way hash that obscures the ip and that's already implemented in mediawiki. It's called creating an account. -- Nx talk 09:07, 3 February 2009 (EST) - Yes, but it's easy to forget to activate it. Evil word Phantom Hoover! 12:09, 3 February 2009 (EST) A translation and algorithms. Lets say you are connecting from the IP address 10.42.69.1. Lets convert these four bytes (the number can only be in the range of 0-255) to hex which is conveniently two hex characters. 10 becomes 0A, 42 becomes 2A, 69 becomes 45 and 1 is 01. The IP address is now 0A2A4501. The unix function crypt() is used for changing 8 character passwords into something that you can't work backwards from. It takes two parameters - the string and some 'salt' that is used to alter the data slightly. crypt('0A2A4501','rw') returns rw/kcy8uTbpIAM. The salt was put at the start as a reminder of what the salt is. If the salt remains constant and hidden, you don't need to put it there. This gives us 'name' of '/kcy8uTbpIA' which is very likely unique to one ipaddress. For someone to reverse engineer this to an ip address without knowing the salt they would need to encrypt every IP address with both upper and lower case form ('0A' vs '0a') and possibly mixed if the coder was a bit more inventive ('0A2a4501' - alternating case) with every possible salt (256 salts). There are 4.3 billion ipv4 addresses - double that for 'A' vs 'a' and another 256 times more for the salts. This is 2.2 trillion (2.2 * 1012 in case anyone gets confused about American numbering beyond a million) possible strings that need to be encrypted. On this old sun I work on (that is still more powerful than the average desktop today and isn't encumbered by microsoft operating systems) I can do about 3600 crypts per second. It would take on the order of 20 years running nonstop at 100% cpu to get the entire set of ip addresses encrypted to match one encrypted one here. The average time would be half if you were just looking for one - still, 10 years. Doing this form of a one way hash to obscure ip addresses would make it impractical for anyone to reverse the hashed ip address back to the numeric one. Other one way hash functions can be used such as md5 which would make it even more secure and difficult to reverse (the time becomes billions of years with current technology). For effect, my sig this time is what it would look like for me as a desalted hashed ip. This IP is currently not blocked at CP (feel free to try to reverse it). --Empkec5ljHk 16:37, 3 February 2009 (EST) Here is an issue with practicality. I can not encrypt the IP that is actually stored in the database, that would for sure break things such as blocking, and probably half the wiki as well since any lookups to that field would violate expectancy. The issue is then that I have to encrypt the display variable whenever it would appear, and there are many places that it could display. I would have to manually alter it in the recentchanges code, the diff code, the history code, the signature code, etc. All in all I think the scope of such a project exceeds its usefulness. tmtoulouse 16:48, 3 February 2009 (EST) - Instead of making them invisible by hiding them, Couldn't one of our JavaScriptCodeXperts play with (Math.floor(Math.random()*256)(4 times) so that everyone could have a random IP sig to make them invisible like: "HnAeYeSdTlAeCK"? (who's bored?) (Toast) and marmalade 13:20, 4 February 2009 (EST) Sidebar[edit] Somewhere (?) there was a conversation about adding stuff to the side bar. I mentioned "All logs" & it was, if not acclaimed, at least not damned. I've done it & put it in "navigation", as you'll see. I would have put it in "toolbox" but couldn't find it. Meeteth it with approval? (Toast) and marmalade 09:24, 2 February 2009 (EST) - It's not possible to put it in the toolbox without javascript hacking (or php hacking), but it's possible to put it below the support link. The conversation was at Mediawiki talk:Sidebar#Adding btw. -- Nx talk 09:29, 2 February 2009 (EST) - Thanks for the location, Nx; I've dropped a note there. I think it's OK where I've put it, actually. (Toast) and marmalade 09:39, 2 February 2009 (EST) - Yeah, that's great where it is. ħuman 16:28, 2 February 2009 (EST) - Embarassingly, CP has had that feature for a long time. ГенгисIs the Pope a Catholic? 08:03, 3 February 2009 (EST) - Where d'you think I got the idea? (Toast) and marmalade 08:54, 3 February 2009 (EST) Can we have lurkers come out day?[edit] Please. It'd be fun... Sterilerationalize 21:44, 2 February 2009 (EST) Consider it done! Sightblinder 02:48, 3 February 2009 (EST) - Peek-a-boo! Aboriginal Noise Oh, what a lovely tea party! 07:16, 3 February 2009 (EST) - As in coming out? Bondurant 07:33, 3 February 2009 (EST) - Whatever happened to our Lurker? ГенгисIs the Pope a Catholic? 08:04, 3 February 2009 (EST) Troubling...[edit] Want to know who gave how much to the Prop. 8 campaign in your neighbourhood? Click here. Even though i'm totally anti- Prop 8, I'm really not sure about the sentiment behind this--I foresee many, many borken windows and other hassles...TheoryOfPractice 09:33, 3 February 2009 (EST) - What gets me is the average amount seems to be about $5000 and from retired people. (Toast) and marmalade 09:42, 3 February 2009 (EST) - How does a "truck driver" afford $2200 to fund a gay marriage proposal? Is it even accurate, though, as surely that info would be confidential. Or more specifically, why would anyone want to give $2200 to a political campaign? I mean, at best, that's a lot of vodka and weed, at worst Oxfam, Christian Aid, The Red Cross, Cancer Research or whatever could do a lot with that kind of cash. ArmondikoVpathetic 10:41, 3 February 2009 (EST) - 450 grand from the Templeton foundation, f**k... ArmondikoVpathetic 10:42, 3 February 2009 (EST) - We should expand our Templeton Foundation article. I'd never heard of it before, but having looked it up on WP, it looks like the foundation has links with a lot of dubious right-ring causes (Discovery Institute, Proposition 8, various think tanks). ŴêâŝêîôîďMethinks it is a Weasel 12:39, 3 February 2009 (EST) - To answer your question, Armond, I have one simply thing to say... The only thing that all religions have in common is that they're great as raising money. I'm still yet to hear any argument against gay marriage that doesn't fall back on some Religious principle. As such, when the medicine man calls for money, the sheep give till it hurts. Religion is probably the second best factor (after good advertising) to get people to work against their own self interest. SirChuckBFurther bulletins as events warrant 14:10, 3 February 2009 (EST) - So when you give money for "the new church roof" (why is it always a new roof they need?!?) the money is actually going to homophobic causes. Pretty sad really. It's like all the people giving to Mother Teressa thinking they were helping people when at least 50% of it went on setting up Catholic missions across the world and the rest was spent on f**k knows what, but it wasn't medicine. ArmondikoVpathetic 10:16, 4 February 2009 (EST) Metapedia[edit] Anyone want to improve the Wikiindex article about Metapedia? Proxima Centauri 14:17, 3 February 2009 (EST) - It's puzzling how big Hungarian Metapedia is, if those article stats are accurate. ŴêâŝêîôîďMethinks it is a Weasel 21:42, 3 February 2009 (EST) - How can I join anonymous? That way I can take down Metapedia. And Conservapedia. And maybe RationalWikiWiki, for about 3.14 milliseconds. If it's at night, no one's there, etc. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 21:43, 3 February 2009 (EST) - First get an email adress that can't be traced to you if you haven't already got one. You need email confirmation to edit. Then choose a unsename. A very "Aryian" name like, 'Horst' or 'Siegfried' might or might not be suspected. I don't know the site. — Unsigned, by: 87.114.19.29 / talk / contribs CUR--don't go there. Metapedia is the worst place on the internet and not something to be trifled with. These people are very, very, very bad and are best left undisturbed. They are way more experienced with online nastiness than you are, and there is NOTHING you can do to upset them, shut them down, or hurt them....taking out an account to call them the scum that they are won't make a bloody bit of difference and if you somehow mess up and leave some sort of clue as to who/where you are, you will have done so with people who are demonstrably unhinged and into violence. Leave it alone, really....TheoryOfPractice 16:12, 4 February 2009 (EST) - Oh, I have no intention of registering. But overloading their server? Completely different. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 16:15, 4 February 2009 (EST) Denial of Service is aparently legal in a few countries. We have no idea where UndergroundResistor is. If it's illegal where you are take great care. The police can trace your computer even if you use prosies proxies. Proxima Centauri 08:06, 5 February 2009 (EST) Finding out if Denial of Service is illegal where you live is easy. I just typed "Denial of Service+UK+law" into Google and found out it's illegal here. There could be RationalWikians living in places where Computer law isn't up to date. Proxima Centauri 09:26, 5 February 2009 (EST) - And, I suspect, illegal. Evil word Phantom Hoover! 16:17, 4 February 2009 (EST) - Nope. Just submit a lot of page views. All you're doing is having their server be so busy, it crashes. Completely legal. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 16:19, 4 February 2009 (EST) - If you're obviously doing it with the intent to crash the server, then it may well be illegal, depending on the laws of your country or state. It's also a silly way to get your kicks. My advice is to leave it alone. ŴêâŝêîôîďMethinks it is a Weasel 16:35, 4 February 2009 (EST) (unident) Anonymous does it all the time. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 16:36, 4 February 2009 (EST) - Doesn't make it legal. Evil word Phantom Hoover! 16:39, 4 February 2009 (EST) - Then why isn't the FBI tracking Anonymous activities? Anonymous would have been caught by now if they actually were engaging in cyber-terrorism. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 16:41, 4 February 2009 (EST) - Look, CUR--I'm trying to help you here--we all are....You've just admitted to intending to do something of dodgy legality against a website owned and operated by neo-Nazis. YOU NEED TO RECONSIDER. Dude, don't be an idiot--between the law, the crackers at Metapedia and your parents, somebody is going to find you out and kick your ass. TheoryOfPractice 16:46, 4 February 2009 (EST) - Do you really think that I have the resources to do such a thing? I can't even do any damage to CP, for Darwin's sake. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 16:49, 4 February 2009 (EST) Good. Now get to work on the Darwin paper. TheoryOfPractice 16:50, 4 February 2009 (EST) Anything new 'round here?[edit] -- 侍 16:33, 3 February 2009 (EST) Hitler and religion[edit] I don't know if you're aware of this, but it appears that you have two different sections on the relationship between Hitler/Nazism and religion which seem say two rather different things: Positive_Christianity and Nazi#Religion_in_National_Socialism. It's not at all a subject I know very much about, but I just noticed. LadyLuck 21:04, 3 February 2009 (EST) - I don't see how. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 21:07, 3 February 2009 (EST) - It's been pointed out before, & the articles do need to be straightened out. I'm no expert either, but I did start trying to research it a while back. Basically, as I see it, Hitler promoted Positive Christianity as a propaganda tool, but seems to have privately been very negative about Christianity. Hence some atheists associate Hitler with Christianity, some Christians associate Hitler with atheism, hence the confusion. ŴêâŝêîôîďMethinks it is a Weasel 21:28, 3 February 2009 (EST) Darwin Paper[edit] I am writing a paper on Darwin for a school project. Anyone have any ideas? --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 21:11, 3 February 2009 (EST) - Review the new book that argues that Darwin was inspired by the Abolition movement. Read Bury the Chains for background. TheoryOfPractice 21:15, 3 February 2009 (EST) (EC, AAAAAAAARRRRRRRRGGGGGGGGGGGGGHHHHHHHHHHH) - I already have the review. Here is what I have so far: - Ideas of evolution go back to very early times in human history. Classical Greek thoughts could be divided into two categories: those who acknowledged some form of evolution and those that denied any form of evolution, and are akin to today’s creationists. Anaximander and his contemporaries believed fell under the first category, believing that that nature was literally alive and that it could change itself, that somehow it created itself, but that it had no order or purpose. Anaximander believed that all living things were created when the sun warmed some primordial element of the earth. Before Socrates, this applied to everything. Anything could come from this matter- and everything did. Plato thought that the real world was a world of unchanging forms, and that everything that exists never changes. He believed that the things perceived were imperfect interpretations of idealized forms that never changed. Any imperfections or differences were caused by the senses distorting things. This meant that if tigers started having glow in the dark stripes, it is not because of radiation, it is because our perceptions have changed. I would attempt to tell that to Godzilla, but he ate me. Aristotle believed that animals and plants represented a line from the least complex to the most complex. However, he saw that the categories were blurred. Basically, he saw a hierarchy, but acknowledged that the lines were blurred. - Approximately 1500 years after Anaximander first had an inkling of evolution, Christianity had become the dominant ruler of science. Scientific thought did not fall far outside of traditional Christian thinking. Some thinkers thought that species could change, but they tried to find evidence in scripture. Most of the arguments for why species had to be designed had to do with scientists feeling that nature was so well designed that a designer had to be involved. For example, one book by leading scientist John Ray was known as The Wisdom of God Manifested in the Works of Creation. In it, Ray argued for the idea of final causes, using the eye as an example- an example which is still used today by creationists. Ray also attempted to back up his argument using woodpeckers, claiming that their stiff tail feathers, short but strong legs, and long tongue were evidence of a designer. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 21:18, 3 February 2009 (EST) - I thought the paper was on DARWIN. not Anaximander. What grade is this for? TheoryOfPractice 21:26, 3 February 2009 (EST) - Very funny. The paper is longer than one paragraph. Darwin contributed to evolution. Does it make any sense not to report on the people before him? --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 21:28, 3 February 2009 (EST) - That depends--how long is the paper? if it's a 500 word thing, then no. if it's 1500 words, you might have room for a brief paragraph--it also depends on what you're arguing in the paper--that will determine what sort of background is relevant. TheoryOfPractice 21:33, 3 February 2009 (EST) (unident) I didn't want to do it this way. I was coerced into doing it this way. Don't blame me. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 21:36, 3 February 2009 (EST) - Look, kid--this is what I DO. Answer my questions, I'll see if I can help--hell, e-mail me a draft if you want...TheoryOfPractice 21:38, 3 February 2009 (EST) - I do not know how long the paper is. The class I am writing it for is as disorganized as RationalWiki is during HCM -2000. The computers don't even have a decent word proccesing program, only textedit. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 21:41, 3 February 2009 (EST) - Jesus Christ, it's like pulling teeth with you. Is it a history class? What grade are you in? What does the teacher/professor want? Was there an assignment handed out? Did he/she just say "write a paper," or did you get any guidelines? TheoryOfPractice 21:45, 3 February 2009 (EST) - Here are some helpful tips for writing a good paper. CorryI think hallucinations are a side effect of Teamocil. 22:12, 3 February 2009 (EST) Cug, Theory is trying to determine the paper's guidelines and target audience. You must have some notion of how long the paper is expected to be. Were you thinking thirty pages or one page? Depending on the answer, one would approach it in an incredibly different manner. I will say that your example paragraphs would seem appropriate for a two or three page paper - is that for what you were aiming? No matter what you do, it is widely considered good form to lead with your thesis statement. There is some wiggle room for an introductory "hook," but at your level I think your teachers would appreciate a greater adherence to more formal form (not meant to be offensive, just based on what I know of high school teachers). Consider your overall approach and what you intend to do with the paper, and develop a single basic sentence that summarizes your view on your topic. Then follow that up with a few supporting statements that will form the substance of each paragraph. If stuck or in a tight spot, taking this fundamental approach is a sure-fire way to achieve at least a mediocre paper if not better. Of course, it would help if you actually told us something about the paper's topic (surely it's not just "Write about Darwin") and the class.--Tom Moorefiat justitia ruat coelum 07:57, 4 February 2009 (EST) - If you'd like me to read a draft, you can email me a copy or paste it here. From what you've already posted, two things; first, your paragraph is a little disorganized. A paragraph, even an intro, should have one topic and stick to it. Second, assuming this is an academic paper, leave out the snark about Godzilla (or any snark for that matter). Z3rotalk 09:54, 4 February 2009 (EST) - The comments made above about structure all seem very sensible. I would also suggest that you might wish to mention Darwin - the subject of the work - in the introduction. Then tell people why you feel it is necessary to launch into the history of the theory of evolution. As has been pointed out by others, the amount of space you devote to he history of evolution will depend on the size of the paper and where you are going with it, but at the moment it looks like you're writing a "history of evolution" paper.--Bobbing up 10:50, 4 February 2009 (EST) Breaking news...[edit] From WIGO, real world (that I don't think anyone reads): Ben Stein withdraws from a commencement speech after widespread protest. The Discovery Institute bitches and moans. - Nice add it to WIGO world. - User Failed to parse (PNG conversion failed; check for correct installation of latex and dvipng (or dvips + gs + convert)): \scriptstyle-i\ln(-1) 22:51, 3 February 2009 (EST) - How the hell did he even get picked for UVM? We're talking Vermont here, they elect socialists and stuff. ħuman 00:02, 4 February 2009 (EST) - This has been blogged by PZ Myers on Pharyngula. He encouraged people to email UVM to stop Stein giving an address. ГенгисIs the Pope a Catholic? 06:21, 4 February 2009 (EST) - I read WIGO:World. And I liked this one. Stein is having a cry about it inside, you can tell. But I definitely agree with the idea that he's done this deliberately just to appear victimised. ArmondikoVpathetic 10:12, 4 February 2009 (EST) - It's a shame that Ben Stein became a shill for the Discovery Institute. His game show was so brilliant. CorryI think hallucinations are a side effect of Teamocil. 12:18, 4 February 2009 (EST) Policy link on Special:BlockIP[edit] The policy link on Special:BlockIP currently links to a joke page. I think we should change this to something more serious, for example RationalWiki:Community_Standards#Blocking or RationalWiki:Blocking policy (if/when that gets updated)? -- Nx talk 06:51, 4 February 2009 (EST) So, any comments? -- Nx talk 15:25, 4 February 2009 (EST) - Agreed. The latter page is more specific and would probably be a better choice of link. KlapauciusEsteemed Constructor 15:28, 4 February 2009 (EST) Where we are now[edit]ГенгисIs the Pope a Catholic? 08:39, 4 February 2009 (EST) - No Professors? No military ranks? No Pagans, Confucians or Vodouns? Perhaps the FCO lost them on a train. Totnesmartin 08:43, 4 February 2009 (EST) - I'm applying for jobs at present, so having to fill in a lot of equal opportunities monitoring forms. On the religion section, some of them have separate boxes for "atheist" and "no religion", which is kindof puzzling. As an atheist, do I tick the atheist box, or is that implicitly defining my atheism as a religion? ŴêâŝêîôîďMethinks it is a Weasel 08:57, 4 February 2009 (EST) - Interesting, but those are all official titles you can use because they're essentially awards. I've never quite figured out the Master one, isn't that just any boy under 12 or something!? ArmondikoVpathetic 10:08, 4 February 2009 (EST) - British Airways have an even longer list. I always amuse myself by picking a random title each time I fly. Last time I was Rear Admiral. You never know, it might even defeat the terrorist watch list. --JeevesMkII 10:19, 4 February 2009 (EST) - But of course, it's much more fun when you can type in your own. Although most people will just go "Jedi" and that's it. I try for a little more imagination Lectitio Divinitatus or perhaps 3rd Day Advent Sheep Shagger... but I can imagine they'd look at you and think you were crazy with that last one. ArmondikoVpathetic 10:24, 4 February 2009 (EST) - Ghengis - what were you doing at the FCO and why did they need your religion? I can't tell from the form whether this is the start of a job application or whether you're planning to travel. Silver Sloth 10:33, 4 February 2009 (EST) - It's for their LOCATE service, essentially you register with them when you visit a foreign country so that they can coordinate help in the event of an emergency. So if I'm drowned by a tsunami in Thailand or buried in an earthquake in Greece then they know which shaman to send to mutter over my corpse. Or something like that. ГенгисIs the Pope a Catholic? 11:41, 4 February 2009 (EST) - Well it's important that, if you get killed in a disaster, you feel OK about it. Totnesmartin 12:25, 4 February 2009 (EST) - This discriminates against pastafarians, IPUists, teapotists and Moonies. Evil word Phantom Hoover! 16:19, 4 February 2009 (EST) Goat arrested in Nigeria[edit] I am shocked to learn that a goat has been arrested in Nigeria. I have updated our goat article but I feel that, as a group, we should formally protest this outrage to our mascot.--Bobbing up 08:49, 5 February 2009 (EST) - We already had that dicussion. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 09:06, 5 February 2009 (EST) - Yes? Sorry, I'm not around so much these days.--Bobbing up 09:14, 5 February 2009 (EST) - I've written it up. Proxima Centauri 11:46, 5 February 2009 (EST) Modified Quote Generator[edit] I'm making a modified qoute generator here: User:ConservapediaUndergroundResistor/modifiedquotegenerator. Anyone got some ideas? --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 09:30, 5 February 2009 (EST) - What's wrong with the old one? Bondurant 09:40, 5 February 2009 (EST) - Not enough lulz. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 09:43, 5 February 2009 (EST) - If your quote generator adds as many lulz to this site as all those lulzy Fall Down socks you keep creating, then Rationalwiki had better come with a "danger, this site may split your sides with laughter" health warning. Bondurant 09:47, 5 February 2009 (EST) - Sorry, did someone ask for a lulsy Fall Down sock? Fall Back 09:51, 5 February 2009 (EST) - So you like the Fall Down socks? --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 09:53, 5 February 2009 (EST) - For the record, "Fall in a positive direction along the imaginary axis" was me. Evil word Phantom Hoover! 12:11, 5 February 2009 (EST) - Hello. -Fall On a Non-Isometric Angle - Hi there. - Simply Obeying Gravity's Well 17:25, 5 February 2009 (EST) New Meta-category(gories?)[edit] - This discussion was moved here from talk: Main Page. We have Pseudoscience, Science etcetera can we have fun and maybe recipe as categories? Mostly I want a category to put Category:Smileys in. We probably should one day go through all the images and catalogue them, but that is a big project so we may need a few weeks organisation to do that, but we could start with a meta-category images. - User Failed to parse (PNG conversion failed; check for correct installation of latex and dvipng (or dvips + gs + convert)): \scriptstyle-i\ln(-1) 22:45, 4 February 2009 (EST) - I agree with the idea of more giant categories. I'm currently focusing on cleaning up the categories we already have, but when I'm done I would be happy to help with any such project. Radioactive afikomen Please ignore all my awful pre-2014 comments. 23:04, 4 February 2009 (EST) - That reminds me... I tried to mass-cat all the templates once, but it didn't go over very well (although I think that had more to do with my attitude back then than the idea). Radioactive afikomen Please ignore all my awful pre-2014 comments. 23:04, 4 February 2009 (EST) - Damn templates, most of them are in a category called category:templates. We are going to need some big work. Once we get the feel from the mob about the meta categories, I think we could make a start about checking that every page is at least one category that goes back through the category to the mainpage. Evilutionist may have abandoned the tree of life but we won't give up on the tree of articles. - User Failed to parse (PNG conversion failed; check for correct installation of latex and dvipng (or dvips + gs + convert)): \scriptstyle-i\ln(-1) 23:11, 4 February 2009 (EST) - A friendly word of warning: mass catting initiatives often rub Human the wrong way. Expect him to pop up and grumble at you at some point. Radioactive afikomen Please ignore all my awful pre-2014 comments. 00:48, 5 February 2009 (EST) - Perhaps we should get all bureaucratic and make a page to discuss this? Those that care can chime in, and perhaps when an idea is forthcoming we could even pretend to "vote"? HAhahahaahahaha ħuman 01:44, 5 February 2009 (EST) - I take it RA that Human is not your biggest supporter when it comes to your organising. - User Failed to parse (PNG conversion failed; check for correct installation of latex and dvipng (or dvips + gs + convert)): \scriptstyle-i\ln(-1) 06:38, 5 February 2009 (EST) - I've started categorising some images. I don't think all images need a category, just ones where we have a lot of pictures of a similar kind sprinkled across different pages, as it makes them easier to find when you need them, or pictures of a kind where a gallery might be appreciated. So far I've made an animal images category (inevitably includes subcats for cats, goats). Please add anything to these that I've missed. I think we should also have an image category for religious art, maybe one or two others. PS. What's category:categories for? PPS. I'm moving this discussion to the bar. ŴêâŝêîôîďMethinks it is a Weasel 14:33, 5 February 2009 (EST) - I have been using category:categories as a meta-category. The image definitely all need at least one cat if not more, I was once trying to find a picture of a blackhole and only came across one by luck. Ken's puffer fish has been uploaded a couple of time so if it was both in conservapedia related media and fish that would be less likely to happen. The names can be stupid why is banana.jpg or what ever a picture of Neptune? Because of an old in-joke which is no help if someone needs a picture of Neptune. - User Failed to parse (PNG conversion failed; check for correct installation of latex and dvipng (or dvips + gs + convert)): \scriptstyle-i\ln(-1) 23:31, 5 February 2009 (EST) - We need a mediawiki namespace catergory. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 14:40, 5 February 2009 (EST) - No we don't it is the only namespace small enough to navigate around and it will only draw your attention to certain pages. - User Failed to parse (PNG conversion failed; check for correct installation of latex and dvipng (or dvips + gs + convert)): \scriptstyle-i\ln(-1) 23:31, 5 February 2009 (EST) - Special:Allpages can display all pages in any namespace, and Special:Allmessages displays all system messages. Evil word Phantom Hoover! 15:26, 5 February 2009 (EST) Some stuff I found on MediaWiki[edit] This might be useful. We could use it to prevent vandalism to specific sections of articles, but not have to lock the whole article. This, if anything, is even better- we could use it for all sorts of things. Not so sure about this one. This one is pretty cool, though. Same here. I don't know what this one does. But this one would almost certainly be popular. Oh noes! Diplomacy! And here's teh news. This would streamline uploading. Any other ones? What does teh mob think? --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 14:56, 5 February 2009 (EST) - Fail2ban blocks IPs that get the password wrong too many times, and is of little use to us. Evil word Phantom Hoover! 15:24, 5 February 2009 (EST) - Oh. Well, what about the others? --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 15:27, 5 February 2009 (EST) - I think we only add new extensions if we're sure they're going to be useful, & most of those I can't really see the point of (for us anyway). Do you have any specific plans for them? ŴêâŝêîôîďMethinks it is a Weasel 15:29, 5 February 2009 (EST) - The poll would enable enhanced polling- people would be able to select one of several options. User snoop would enable us to track specific users. The news channel would be good for WIGO World. As for the diplomacy, we could form stronger ties with other wikis this way. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 15:32, 5 February 2009 (EST) - We don't even have checkuser; why the hell would we have user snoop? Evil word Phantom Hoover! 15:35, 5 February 2009 (EST) - EC) There are more extensions in heaven and earth ... Seriously, It's up to Trent: He's the one who'd have to install, maintain & troubleshoot any extensions. I'd imagine we've all been through the list and been like kiddies in Santa's grotto. (Toast) and marmalade 15:37, 5 February 2009 (EST) - (EC)If we don't want it, fine. Just a suggestion. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 15:38, 5 February 2009 (EST) The idea is to add extensions/functions/whatever that we need to do things. If you come to me and say "I think we should have x because we can use it to do y and y is important because of z" I am pretty good about eventually getting it installed. Otherwise it is just tech creep. tmtoulouse 15:53, 5 February 2009 (EST) - Protecting certain parts of articles might be interesting, but we have so many sysops who'd have to understand what was going on it might just be chaos. The poll function might be nice - in fact, we could reopen the voting debate. :-) Guestbook doesn't convince me. News Channel - Mmmm - would we use it? Actually I can't really see a need for any of them - though they might be fun to have.--Bobbing up 16:03, 5 February 2009 (EST) - We definitely should have the poll. As for the news channel, we could use it to promote dicussion of current events. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 16:26, 5 February 2009 (EST) - Have you guys actually looked at how the poll renders? It is really shoddy code, the first generation WIGO voting was cannibalized from this extension because I hadn't learned how to write extensions yet. As soon as I figured out how to do it I rewrote the voting from the ground up because there were so many problems with this code, not to mention it renders like crap. tmtoulouse 16:28, 5 February 2009 (EST) - Polls are easy enough to do with what we've got (adapting WIGO buttons, using sliders, or just voting by signature). I don't thing section protecting would be useful. We protect pages as little as possible anyway, & I can't think of many cases where just one section of an article gets vandalised - only the "see also" section of the Fred Phelps article, & I suspect if that was protected & the rest of the page wasn't, the vanda would still post the link elsewhere on the page. ŴêâŝêîôîďMethinks it is a Weasel 17:03, 5 February 2009 (EST) Hmmm interesting let me look at each one - We don't protect pages so we don't want to protect section, although if someone could convince me it would reduce page lockings then fine. - We already use the parser extension tag <poll> so it would probably destroy the server, definite no. - Snoop seems nearly as invasive as check user, so no. - I can't even work out what guestbook does, any visitor can sign RationalWiki:How_I_found_RationalWiki if they want. - We already have embedded video and flash mp3 player, so if we had the ogg extension we could do all this any way, my vote get the ogg extension. - If people think their account are compromised then fail2login would be okay but most it is going to full of my IP address because of how badly thought out my name is. - Gadgets would be cool, please Trent. - First ambassador wouldn't run on RationalWiki. Second who are we going to ambassador with, CP? Hell will freeze over before our relations with them will. - News channel would be good although I don't know how much it would be used. - Capturebot would the only "person" doing that much uploading and even then it has enough problems without making it compliant with that. Basically we are still having minor server problems following the move so unless these provide something amazing we should avoid unnecessary upgrades until we are stable again. - User Failed to parse (PNG conversion failed; check for correct installation of latex and dvipng (or dvips + gs + convert)): \scriptstyle-i\ln(-1) 03:27, 6 February 2009 (EST) - Gadgets would be nice, but they're not really necessary. I've added the MediaWiki 1.13+ wikibits.js importScript and importStylesheet functions to Common.js, which are essentially the same. Try adding importScript('User:Nx/Scripts/Smileybox.js'); to your monobook.js (or monobook_adfree.js if you use the adfree skin) and try my new smileybar -- Nx talk 13:59, 6 February 2009 (EST) - Who would we be ambassadors with? Wikipedia, AthiesmWiki, RationalWikiWiki, Uncyclopedia, etc. etc. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 15:25, 6 February 2009 (EST) Work in progress[edit] Essay:Conservapedia, the sitcom I have to run out right now, I'll be back to add moar later! ħuman 16:42, 5 February 2009 (EST) - Why not put it in funspace? Evil word Phantom Hoover! 16:50, 5 February 2009 (EST) - Because A) It's Human's Essay; B) It's WIP. (Toast) and marmalade 17:13, 5 February 2009 (EST) Night Mode!?!?![edit] (Note: someone seems to be threatening to develop code for night mode--see here. This is barely even worth talking about, right?) I've not been around these last couple of days, but--WHAT THE FUCK??!?!?!! We're having NIGHT MODE!?!?!? Is this/has this been discussed somewhere? TheoryOfPractice 10:01, 6 February 2009 (EST) - it was discussed as a way of blocking the Poe's law bot attacks, and was taken semi-seriously by a couple of people. I can't see night mode being implemented here ever - we have edits 247, and editors in all faces of the time cube. If it ever goes to a vote (or even a vote about having a vote, and a vote about that vote) I'm against as well. Totnesmartin 10:08, 6 February 2009 (EST) - Riiiight.... because that'll happen. Though hell has been feeling a little chilly recently. ArmondikoVpathetic 10:22, 6 February 2009 (EST) - Also see Talk:Fred Phelps. Neveruse513 10:27, 6 February 2009 (EST) - I hadn't noticed that these attacks happen only at night. Didn't Ben Franklin say something about security and liberty, and what happens between them? I forget. Z3rotalk 10:32, 6 February 2009 (EST) - Who "Ben Franklin"? He editor? (Toast) and marmalade 10:35, 6 February 2009 (EST) - "Those who would give up an essential liberty for temporary security deserve neither liberty nor security" - or something very like it. Worm (t | c) 10:37, 6 February 2009 (EST) - Regardless of when the attacks occur, they will not stop. Freedom is the enemy of security. Night mode is our saving grace and the development of which is progressing smoothly. Neveruse513 10:39, 6 February 2009 (EST) Look, you're prolly just yankin' our chains, and that's fine, but if you're serious, this is a non-starter and will never happen. TheoryOfPractice 10:43, 6 February 2009 (EST) - To be honest, I thought it was much more obvious and didn't imagine it would have to go this far. Neveruse513 10:45, 6 February 2009 (EST) - What about "happy hour mode" when only people who ar drunk can edit? Would be a lot more fun.--Bobbing up 14:11, 6 February 2009 (EST) - YES! Totnesmartin 14:20, 6 February 2009 (EST) - After a review of my night mode code, the "happy hour mode" should only be a small tweak, perhaps only a matter of weeks. Neveruse513 14:24, 6 February 2009 (EST) - The problem is "when" is happy hour? I know that Neveruse513 seems to think that if it's "night" in the US then it's "night" all over the world, but things don't work like that. So when is "happy hour"?--Bobbing up 14:27, 6 February 2009 (EST) - I know the "night" part is throwing everyone off. It's a misnomer. If I could change the name, I would, but I can't, so I won't. Neveruse513 14:32, 6 February 2009 (EST) - EC) For Human, it's any time he's on the net. and marmite 14:33, 6 February 2009 (EST) - (ec) For most user, happy our is every hour. Z3rotalk 14:38, 6 February 2009 (EST) - We can just define night as "whatever time Count RA is online". Evil word Phantom Hoover! 14:44, 6 February 2009 (EST) - I think it's great we're all working together to make this happen, but unless someone knows of some magic program that can globally search my massive code with a regular expression of some sort and print the instances so I can change them, all this fuss over the name is moot. Neveruse513 14:50, 6 February 2009 (EST) - Awwww. You wrote all that code for it to never be used. Evil word Phantom Hoover! 14:51, 6 February 2009 (EST) - We'll see who's laughing at sundown. Neveruse513 14:53, 6 February 2009 (EST) - It's possible that Neveruse513 will find himself writing code to get himself out of the vandal bin.--Bobbing up 14:54, 6 February 2009 (EST) - (EC)In case you haven't noticed, I'm a bureaucrat. Unless your code totally locks the database, which would be stupid, I can circumvent it. Evil word Phantom Hoover! 14:57, 6 February 2009 (EST) - I have many tricks up my sleeve. Also, I am hoping to achieve bureaucrat status in the coming months it will take me to finish development. Neveruse513 14:59, 6 February 2009 (EST) - You really think that we'll make you a bureaucrat if you are trying to insert code into the wiki against the wishes of the mob? Evil word Phantom Hoover! 15:01, 6 February 2009 (EST) - Coming months? I thought nite mode was ready to go at sundown? Z3rotalk 15:03, 6 February 2009 (EST) - There may have been a few small setbacks. But don't push me - we wouldn't want to force my hand and implement some half-baked version of nite moad that could fuck a bunch of shit up. Neveruse513 15:09, 6 February 2009 (EST) - If you implement it at all, a "bunch of shit will be fucked up", then we will see to it that the same happens to you. Evil word Phantom Hoover! 15:15, 6 February 2009 (EST) - And we'll see if it happens during daytime hours. Neveruse513 15:17, 6 February 2009 (EST) - "We"? Evil word Phantom Hoover! 15:18, 6 February 2009 (EST) - Did you really not get the grep joke? Neveruse513 15:19, 6 February 2009 (EST) - Yeah, it's obviously a joke. Evil word Phantom Hoover! 15:05, 6 February 2009 (EST) EC * 3 - Neveruse513 is making CUR look almost reasonable. and marmite 15:19, 6 February 2009 (EST) -) - The simplest way to institute Night Mode would be by creating a bot which would be activated at certain hours of the night, & would automatically block any user (for a few hours, until the end of Night Mode) as soon as they make an edit during these times, as well as automatically reverting their edit. I'll get working on it right away. ŴêâŝêîôîďMethinks it is a Weasel 15:25, 6 February 2009 (EST) - Finally. Someone who understands the need. It's going to take a couple of weeks for me to port my code to .js, so if you have something ready to launch we should go with that. Neveruse513 15:28, 6 February 2009 (EST) - No, no, no and no. We will not instigate night mode unless we have community consensus. Evil word Phantom Hoover! 15:30, 6 February 2009 (EST) - The community is in shambles because of the vandal crisis and you want to take a vote? We're passed that. Stop standing in the way of progress. Neveruse513 15:33, 6 February 2009 (EST) (unident)(EC)Looking for me? I was sick the last two days, but went to school today, so I was absent from the wiki for a few hours. Sorry. I have EC with Neveruse513. He isn't me. I am seriously not kidding. Weaseloid, don't you dare do such a thing. If such a thing would be implemented, then we should only apply to users such as Fall Down. And there's one fatal flaw in Neveruse513's logic- the vandalism was done during the day. I suspect that this guy is a sock. Any sysop here knows that we don't do such things. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 15:34, 6 February 2009 (EST) - Look at this. We are becoming more and more like CP. Weaseloid, you are being irresponsible. Sorry, but you are. You should NOT be helping Neveruse513. We have editors who edit from the other side of the planet. Vandalism is done almost exclusively during the daylight hours, when such a bot would not be implemented. There was no vandal crises. Tit has been doing this for quite a while, and it is fairly easy to deal with. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 15:38, 6 February 2009 (EST) - (EC)How are we in shambles? There has been some annoying vandalism to a couple of articles which was easy to revert, and you're already trying to impose major restrictions on all editors. (Help! I'm agreeing with CUR!) Evil word Phantom Hoover! 15:39, 6 February 2009 (EST) - Wheel War! Z3rotalk 15:40, 6 February 2009 (EST) - I think that only applies to sysops reverting each other's blocks, not bureaucrats warring over rights. Evil word Phantom Hoover! 15:41, 6 February 2009 (EST) - - I have blocked both Neveruse and NightModBot. We won't be seeing from them in a while. Hated to do it, but necessary. Unblock them if you want. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 15:42, 6 February 2009 (EST) - God damn you guys are good. I'm almost convinced that you're serious (about not implementing nite moad). Neveruse513 15:43, 6 February 2009 (EST) - Lighten up, guys. I don't know how many times you need to be told this, but IT'S JUST A JOKE. ŴêâŝêîôîďMethinks it is a Weasel 15:45, 6 February 2009 (EST) - Weaseloid, Neveruse513 isn't taking this as a joke. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 15:46, 6 February 2009 (EST) - I think NU isn't serious either. Evil word Phantom Hoover! 15:47, 6 February 2009 (EST) - GOD DAMNIT I CAN'T TAKE IT ANY MOAR - Are you besting me? Neveruse513 15:48, 6 February 2009 (EST) (unident) I'm almost sure he is. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 15:49, 6 February 2009 (EST) - I remain sceptical, but there is little I can do until I'm sure. Evil word Phantom Hoover! 15:50, 6 February 2009 (EST) - How come, no matter how silly something is, the addition of CUR turns it into a full-blown emergency? Z3rotalk 15:51, 6 February 2009 (EST) - Night mode could have prevented this whole thing. Neveruse513 15:52, 6 February 2009 (EST) - (EC)Stop picking on CUR; I was confused too. Evil word Phantom Hoover! 15:53, 6 February 2009 (EST) - (EC)I am not trying to make this an emergency. NU brought this up on several pages. Every possible indicator has been made that this is not funny. If this was a joke, he would have given it up. PH, you can't deal with NU- but you can deal with the bot. I already did, of course. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 15:54, 6 February 2009 (EST) - I thought I made it clear multiple times that this was a joke. You guys kept going. I mistook it for uber-sarcasm, which get's me all hot and ready. If you're not doing uber-sarcasm, just stop responding, because I'll never know. Otherwise, this will go on as long as it has to (i.e. night mode implementation). Neveruse513 15:56, 6 February 2009 (EST) - Did you? Where? Evil word Phantom Hoover! 15:57, 6 February 2009 (EST) - (EC x 2) CUR, read through Neveruse513's posts in this thread & on the Fred Phelps page. I think he/she has acknowledged it was a joke at least three times. You & Hoover took no notice so he/she's carried on with it. That is all. ŴêâŝêîôîďMethinks it is a Weasel 15:58, 6 February 2009 (EST) - I tend to get confused when people keep changing position from "joke" to "apparently serious". Evil word Phantom Hoover! 16:01, 6 February 2009 (EST) Here's the first (and most obvious time): - It's a joke! Can't you take a joke? And if you do try hacking, we'll find a way. We always do. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 15:16, 5 February 2009 (EST) - Unless you're out-sarcasming me, I suggest you take your own advice. The mention of "Computer Science III" also should have been a dead giveaway... Neveruse513 16:02, 6 February 2009 (EST) - Why? (I'm only familiar with British curriculums.) Evil word Phantom Hoover! 16:05, 6 February 2009 (EST) - It's a 4chan meme...I guess it's not obvious outside that context. Sorry. Second attempt to make this clear: Look, you're prolly just yankin' our chains, and that's fine, but if you're serious, this is a non-starter and will never happen. TheoryOfPractice 10:43, 6 February 2009 (EST)Neveruse513 16:07, 6 February 2009 (EST) - To be honest, I thought it was much more obvious and didn't imagine it would have to go this far. Neveruse513 10:45, 6 February 2009 (EST) - (EC x3) I don't understand Computer Science III either, but I thought the whole thing was very obviously a joke from the outset. Considering how much we talk about Poe's Law, people at this site seem to be terrible at differentiating parody from serious suggestions. ŴêâŝêîôîďMethinks it is a Weasel 16:08, 6 February 2009 (EST) - It's not really a great meme. Neveruse513 16:12, 6 February 2009 (EST) - I have a tendency to trust people on their word too much. Evil word Phantom Hoover! 16:09, 6 February 2009 (EST) Third attempt: -) - I know that it was made clear in places, but this discussion is large, and I tend to only look at the active ends. Evil word Phantom Hoover! 16:12, 6 February 2009 (EST) - Fair enough. Sorry for trolling you, I honestly thought you were trolling back. Neveruse513 16:14, 6 February 2009 (EST) - Same here. I only saw the active bits- and my sarcasm meter broke yesterday. I was attempting to fix my wierdness meter (keeps breaking whenever I touch it) and it blew a gasket, shattering the meter on the sarcasm meter. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 16:16, 6 February 2009 (EST) - "" Evil word Phantom Hoover! 16:16, 6 February 2009 (EST) So -I got lost in all the discussion. When are we introducing Night Mode? DogP 16:18, 6 February 2009 (EST) - Weaseloid's apparently got something in the works. Maybe we can go beta before sundown? Neveruse513 16:21, 6 February 2009 (EST) - Yaaaay! Evil word Phantom Hoover! 16:27, 6 February 2009 (EST) - Hurry the fuck up with nite moad already. It's already dark here. Bondurant 16:30, 6 February 2009 (EST) - Maybe it's already up and you simply have nite moad privileges. Neveruse513 16:31, 6 February 2009 (EST) - I can has nite moad privileges? Bondurant 17:10, 6 February 2009 (EST) - You already have them. All existing editors do. Neveruse513 17:12, 6 February 2009 (EST) I have used my credibility built up for over a year of editing here coupled with my mastery of BASIC to unilaterally institute night mode restrictions across this site. Owing to the apparent roundness of the globe and the associated persistence of night at all times somewhere, night mode will be active at all times with the possible exception of leap days, hours and seconds (damn that Y2K bug). I apologize for doing this without discussion but, given the relentless onslaught of wizard ninja vandals, I felt compelled to save the world the only way I know how -- through "Hello World" programs in archaic coding languages. That is all. Exasperate me!Sheesh!Not the most impressive contributor here 16:44, 6 February 2009 (EST) - Using my 1337 h4xx0r skillz, I have locked you all out of editing. Mwuhahahaha -- Nx talk 17:19, 6 February 2009 (EST) - Have not. --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 17:20, 6 February 2009 (EST) - Good one, Nx, but I can disable JavaScript. Evil word Phantom Hoover! 17:21, 6 February 2009 (EST) - You, sir, are a patriot and RW is in your debt for your efforts. The implementation of Night Mode is imperative. Neveruse513 17:23, 6 February 2009 (EST) - yawn* --"ConservapediaUndergroundThermistorRusty-spotted catspeed! 17:25, 6 February 2009 (EST) - I'm a little surprised you don't somehow still think I'm serious. Neveruse513 17:28, 6 February 2009 (EST) - The best trick the devil ever played was to convince people that he didn't exist. Exasperate me!Sheesh!Not the most impressive contributor here 23:16, 6 February 2009 (EST) EZ Edit Button[edit] Javasca₧ no hell below him - SAGE GOES IN ALL FIELDS! Chris Fanshaw 20:50, 6 February 2009 (EST) - It's also a good flavouring for sausages, stuffings, potatoes and pork dishes. ŴêâŝêîôîďMethinks it is a Weasel 09:48, 7 February 2009 (EST)
https://rationalwiki.org/wiki/RationalWiki:Saloon_bar/Archive5
CC-MAIN-2022-21
refinedweb
14,078
73.68
fchdir() Change the working directory Synopsis: #include <unistd.h> int fchdir(int fd); Since: BlackBerry 10.0.0 Arguments: - var - A file descriptor for the directory that you want to become the current working directory. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. Description: The fchdir() function is similar to chdir(), except that you use a file descriptor to specify the directory that you want to become the new current working directory. You can obtain a file descriptor for a directory by calling open(), provided that the file status flags and access modes don't contain O_WRONLY or O_RDWR. Returns: 0, or -1 if an error occurred ( errno is set). If the function fails, the current working directory isn't changed. Errors: - EACCES - Search permission is denied for the directory referenced by fd. - EBADF - The fd argument isn't an open file descriptor. - ENOTDIR - The open file descriptor fd doesn't refer to a directory. - EINTR - A signal was caught during the execution of fchdir(). - EIO - An I/O error occurred while reading from or writing to the filesystem. Classification: Last modified: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/f/fchdir.html
CC-MAIN-2015-18
refinedweb
213
59.5
Groovy has powerful SQL support to work with in our scripts and classes. It is all based on JDBC, but so much easier to code. For example to create a connection to a database we only need one line of code and we get a powerful object in return. With this object we can run queries and SQL statements to manipulate data. In this post we look at the basic SQL support in Groovy. In a next post we learn a more powerful Groovy SQL feature: DataSets. In the following code snippet we are accessing a MySQL database with the name groovy. Both username and password for the database are groovy and MySQL is running on localhost and port 3306 (is default port). import groovy.sql.* def username = 'groovy', password = 'groovy', database = 'groovy', server = 'localhost' // Create connection to MySQL with classic JDBC DriverManager. def db = Sql.newInstance("jdbc:mysql://$server/$database", username, password, 'com.mysql.jdbc.Driver') // Or we can create a connection with a DataSource (also via JNDI possible) def ds = new com.mysql.jdbc.jdbc2.optional.MysqlDataSource( databaseName: database, user: username, password: password, serverName: server ) assert 'jdbc:mysql://localhost:3306/groovy' == ds.url def dbDS = new Sql(ds) // Create a new table db.execute 'drop table if exists languages' // We can use multi-line strings to create readable SQL in our code. db.execute ''' create table languages( id integer not null auto_increment, name varchar(20) not null, primary key(id) ) ''' // Fill table with data in different ways. // First a normal statement. db.execute 'insert into languages values(null, "Groovy")' assert 1 == db.updateCount // String with extra parameters will become a prepared statement. db.execute 'insert into languages values(null, ?)', ['Java'] assert 1 == db.updateCount // GString will become a prepared statement. def langValue = 'JRuby' db.execute "insert into languages values(null, $langValue)" assert 1 == db.updateCount // With executeInsert we get the generated id(s) back. def insertedIds = db.executeInsert 'insert into languages values(null, "Scalaa")' assert 4 == insertedIds[0][0] // executeUpdate return number of rows affected. def old = 'Scalaa', new = 'Scala' def updated = db.executeUpdate "update languages set name=$new where name=$old" assert 1 == updated // Now let's get data from the table Groovy style. // With rows we get a list of GroovyResultSet objects and this means we can // use column names to access data in a row. def all = db.rows('select * from languages') assert 4 == all.size() assert ['Groovy', 'Java', 'JRuby', 'Scala'] == all.collect{ it.name } assert ['Groovy', 'JRuby'] == all.findAll{ it.name ~= /y/ } // With eachRow we can use a closure to do something with each row. // The closure parameter is also of type GroovyResultSet. def maxId = 3 db.eachRow("select id, name from languages where id < $maxId") { row -> if (row.id == 1) assert 'Groovy' == row.name if (row.id == 2) assert 'Java' == row.name } db.eachRow("select name from language where name=?", ['Java']) { assert 'Java' == it.name } def countRows = db.firstRow("select count(*) as numberOfRows from languages") assert 4 == countRows.numberOfRows 5 comments: It would be nice to show the example with Derby as the JDK already comes with it @Anonymous: The sample can be run with Derby, but then the JDBC url changes to: jdbc:derby:$database;create=true and the driver must be org.apache.derby.jdbc.EmbeddedDriver (if we want to run an embedded database). We can use the org.apache.derby.jdbc.EmbeddedDataSource class to create a DataSource for Derby. The "if exists" is not recognized by Derby so we must change the drop table statement. Be aware that using GStrings for SQL statements opens you up to SQL injections. So best stick to the parameterised versions in SQL involving user input. Which application uses userid/password in plain text? Please include code that is useful for the reader. There is a typo line 62 for the table name: it should be languages instead of language. Your examples are interesting. Thanks for sharing your knowledge.
http://mrhaki.blogspot.com/2009/10/groovy-goodness-groovy-sql.html
CC-MAIN-2014-42
refinedweb
654
61.12
Allowing Multiple Genre Selection It happens. Requirements change. Now we want to allow selecting multiple genres for a movie. For this, we need a M-N mapping table that will let us link any movie to multiple genres. Creating MovieGenres Table As usual, we start with a migration: Modules/Common/Migrations/DefaultDB/ DefaultDB_20160528_115400_MovieGenres.cs: using FluentMigrator; namespace MovieTutorial.Migrations.DefaultDB { [Migration(20160528115400)] public class DefaultDB_20160528_115400_MovieGenres : Migration { public override void Up() { Create.Table("MovieGenres").InSchema("mov") .WithColumn("MovieGenreId").AsInt32() .Identity().PrimaryKey().NotNullable() .WithColumn("MovieId").AsInt32().NotNullable() .ForeignKey("FK_MovieGenres_MovieId", "mov", "Movie", "MovieId") .WithColumn("GenreId").AsInt32().NotNullable() .ForeignKey("FK_MovieGenres_GenreId", "mov", "Genre", "GenreId"); Execute.Sql( @"INSERT INTO mov.MovieGenres (MovieId, GenreId) SELECT m.MovieId, m.GenreId FROM mov.Movie m WHERE m.GenreId IS NOT NULL"); Delete.ForeignKey("FK_Movie_GenreId") .OnTable("Movie").InSchema("mov"); Delete.Column("GenreId") .FromTable("Movie").InSchema("mov"); } public override void Down() { } } } I tried to save existing Genre declarations on Movie table, by copying them to our new MovieGenres table. The line above with Execute.Sql does this. Then we should remove GenreId column, by first deleting the foreign key declaration FK_Movie_GenreId that we defined on it previously. Deleting Mapping for GenreId Column As soon as you build and open the Movies page, you'll get this error: This is because we still have mapping for GenreId column in our row. Error above is received from AJAX call to List service handler for Movie table. Repeating of error message originates from SQL server. MovieId column name passes several times within the generated dynamic SQL. Remove GenreId and GenreName properties and their related field objects from MovieRow.cs: // remove this public Int32? GenreId { get { return Fields.GenreId[this]; } set { Fields.GenreId[this] = value; } } // remove this public String GenreName { get { return Fields.GenreName[this]; } set { Fields.GenreName[this] = value; } } public class RowFields : RowFieldsBase { // and remove these public Int32Field GenreId; public StringField GenreName; } Remove GenreName property from MovieColumns.cs: // remove this [Width(100), QuickFilter] public String GenreName { get; set; } Remove GenreId property from MovieForm.cs: // remove this public Int32 GenreId { get; set; } After building, we at least have a working Movies page again. Generating Code For MovieGenres Table Fire up sergen and generate code for MovieGenres table as usual: As we're not going to edit movie genres from a separate page, you can safely delete the generated files below: MovieGenresColumns.cs MovieGenresDialog.ts MovieGenresEndpoint.cs MovieGenresForm.cs MovieGenresGrid.cs MovieGenresIndex.cshtml MovieGenresPage.cs You can also remove CSS entries for s-MovieDB-MovieGenresDialog from site.less. Only leave last two files, MovieGenresRow.cs and MovieGenresRepository.cs. After building, run T4 templates to be sure, no T4 generated files related to MovieGenresForm etc. is left behind. Adding GenreList Field As one movie might have multiple genres now, instead of a Int32 property, we need a list of Int32 values, e.g. List<Int32>. Add the GenreList property to MovieRow.cs: You might have to add System.Collections.Generic to usings. //... [DisplayName("Kind"), NotNull, DefaultValue(MovieKind.Film)] public MovieKind? Kind { get { return (MovieKind?)Fields.Kind[this]; } set { Fields.Kind[this] = (Int32?)value; } } [DisplayName("Genres")] [LookupEditor(typeof(GenreRow), Multiple = true), NotMapped] [LinkingSetRelation(typeof(MovieGenresRow), "MovieId", "GenreId")] public List<Int32> GenreList { get { return Fields.GenreList[this]; } set { Fields.GenreList[this] = value; } } public class RowFields : RowFieldsBase { //... public Int32Field Kind; public ListField<Int32> GenreList; Our property has [LookupEditor] attribute just like GenreId property had, but with one difference. This one accepts multiple genre selection. We set it with Multiple = true argument. This property also has NotMapped flag, which is something similar to Unmapped fields in Serenity. It specifies that this property has no matching database column in database. We don't have a GenreList column in Movie table, so we should set it as an unmapped field. Otherwise, Serenity will try to SELECT it, and we'll get SQL errors. In the next line, we use another new attribute, LinkingSetRelation: [LinkingSetRelation(typeof(MovieGenresRow), "MovieId", "GenreId")] This is an attribute which is specific to M-N releations that links a row in this table to multiple rows from another table. First argument of it is the type of M-N mapping row, which is MovieGenresRow here. Second argument is the property name of field in that row (MovieGenresRow) that matches this row's ID property, e.g. MovieId. Third argument is the property name of field in that row (MovieGenresRow) that links multiple Genres by their IDs, e.g. GenreId. LinkingSetRelation has a related Serenity service behavior, named LinkingSetRelationBehavior that is automatically activated for all fields with a LinkingSetRelation attribute. This behavior, will intercept service handlers for Create, Update, Delete, Retrieve and List and inject code to populate or update our GenreList column and its related MovieGenres table. We'll talk about Serenity service behaviors in following chapters. Adding Genre List To Form Edit MovieForm.cs and add GenreList property: public class MovieForm { //... public List<Int32> GenreList { get; set; } public MovieKind Kind { get; set; } public Int32 Runtime { get; set; } } Now we can add multiple genres to a Movie: Showing Selected Genres in a Column Previously, when we had only one Genre per Movie. We could show the selected genre in a column, by adding a view field to MovieRow.cs. It is not going to be so simple this time. Let's start by adding GenreList property to MovieColumns.cs: public class MovieColumns { //... [Width(200)] public List<Int32> GenreList { get; set; } [DisplayName("Runtime in Minutes"), Width(150), AlignRight] public Int32 Runtime { get; set; } } This is what we got: GenreList column contains a list of Int32 values, which corresponds to an array in Javascript. Luckily, Javascript .toString() method for an array returns items separated by comma, so we got "1,2" for Fight Club movie. We would prefer genre names instead of Genre IDs, so it's clear that we need to format these values, by converting GenreId to their Genre name equivalents. Creating GenreListFormatter Class It's time to write a SlickGrid column formatter. Create file GenreListFormatter.ts next to MovieGrid.ts: namespace MovieTutorial.MovieDB { @Serenity.Decorators.registerFormatter() export class GenreListFormatter implements Slick.Formatter { format(ctx: Slick.FormatterContext) { let idList = ctx.value as number[]; if (!idList || !idList.length) return ""; let byId = GenreRow.getLookup().itemById; return idList.map(x => { let g = byId[x]; if (!g) return x.toString(); return Q.htmlEncode(g.Name); }).join(", "); } } } Here we define a new formatter, GenreListFormatter and register it with Serenity type system, using @Serenity.Decorators.registerFormatter decorator. Decorators are similar to .NET attributes. All formatters should implement Slick.Formatter interface, which has a format method that takes a ctx parameter of type Slick.FormatterContext. ctx, which is the formatting context, is an object with several members. One of them is value that contains the column value for current grid row/column being formatted. As we know that we'll use this formatter on column with a List<Int32> value, we start by casting value to number[]. There is no Int32 type in Javascript. Int32, Double, Single etc. corresponds to number type. Also, generic List<>type in C# corresponds to an Array in Javascript. If the array is empty or null, we can safely return an empty string: let idList = ctx.value as number[]; if (!idList || !idList.length) return ""; Then we get a reference to Genre lookup, which has a dictionary of Genre rows in its itemById property: let byId = GenreRow.getLookup().itemById; Next, we start mapping these ID values in our idList to their Genre name equivalents, using Array.map function in Javascript, which is pretty similar to LINQ Select statement: return idList.map(x => { We lookup an ID in our Genre dictionary. It should be in dictionary, but we play safe here, and return its numeric value, if the genre is not found in dictionary. let g = byId[x]; if (!g) return x.toString(); If we could find the genre row, corresponding to this ID, we return its Name value. We should HTML encode the genre name, just in case it contains invalid HTML characters, like <, > or &. return Q.htmlEncode(g.Name); We could also write a generic formatter that works with any type of lookup list, but it's beyond scope of this tutorial. Assigning GenreListFormatter to GenreList Column As we defined a new formatter class, we should build and transform T4 files, so that we can reference GenreListFormatter in server side code. After building and transforming, open MovieColumns.cs and attach this formatter to MovieList property: public class MovieColumns { //... [Width(200), GenreListFormatter] public List<Int32> GenreList { get; set; } [DisplayName("Runtime in Minutes"), Width(150), AlignRight] public Int32 Runtime { get; set; } } Now we can see Genre names in Genres column:
https://volkanceylan.gitbooks.io/serenity-guide/tutorials/movies/allowing_multiple_genre_selection.html
CC-MAIN-2019-18
refinedweb
1,426
51.44
Class Format Error: Here,i am going to present what i have learnt when dealing with byte codes in the class file.We all know that whenever a java program is successfully compiled,the class file would be generated.Then you may think how come this ClassFormatError is thrown at run-time. So let's discuss about this error in detail to know the reasons behind them. In the java API documentation it is given that "this error would be thrown when the java virtual machine attempts to read a class file and founds that the class file has been altered in such a way that it loses its integrity." Here they are trying to say that "if a class file has been modified in a complicated way then this error would be thrown." There may be two possible ways a class file can get corrupted as far i know. 1.May be the compiler have some unresolved bugs in it. 2.The programmer may intentionally change the class file for some reasons. You may ask,why am i gonna change a class file? after all it is compiled(and executed) successfully.The fact is that when you want to develop a state-of-the-art application then you must have to deal with byte codes. So here you have to note an important thing that "this error will occur either if someone intentionally modified the class file or your compiler have some bugs in it." I will show you know now how come this error occurs,Before that i want to remind you about the Hex editors.The Hex editors are applications which lets you edit the file that contains the hex codes. Since the class files contains Hex codes,we can able to edit it. I have included a simple program that performs the addition of two numbers and i edited the class file using the hex editor to show you how this error occurs. Program: import java.io.*; import java.util.*; public class Add { public static void main(String args[]) { int a; int b; a=1; b=2; int c=a+b; System.out.println("The value is:"+c); } } Have a look at the Hex codes contained in the class file generated for this program. Consider the line 0C0: 01 00 0D 54 68 65 20 76 in which the second pair of Bytes contains 00(NOP) which means No operation. For the sake of optimizing the program i have changed the value 00 as 1D which loads a integer value from the local variable. But doing so,causes java.lang.ClassFormatError to be thrown during run-time as follows: The change that, i have made results in the truncation of the class file...... Thus while dealing with byte codes in the class file,ensure that you do not try to change the byte codes unnecessarily.Note that,even if you try to change the particular byte codes then you would not get this error,but your ultimate output would get changed. So,while changing the byte codes be conscious about the consequences of your modification.
http://craftingjava.blogspot.com/2012/07/reason-for-javalangclassformaterror.html
CC-MAIN-2017-39
refinedweb
519
70.33
From: Peter Dimov (pdimov_at_[hidden]) Date: 2001-10-18 13:27:11 From: "Jim.Hyslop" <jim.hyslop_at_[hidden]> > Peter Dimov [SMTP:pdimov_at_[hidden]] wrote: > > While we are on the topic: > > > > The article > > > > > > > > asserts that any_cast will work unqualified due to Koenig lookup. However, > > note that it has an explicit template parameter. I'm not sure whether > > argument dependent lookup will work in this case. > The compiler I use doesn't support Koenig lookup, so I blush to admit it's > one of those things I haven't bothered learning all the details about (I > know the general idea, of course). My original code sample qualified the use > of any_cast, but Kevlin assured me Koenig lookup should work. > > I'm not clear how you see that explicit template parameters will affect > Koenig lookup. I've checked the standard, and my reading of 3.4.2 supports > Kevlin's (and therefore my) position. > > Let me explain my reasoning on why I think it should work: > > The name being looked up is a template function named "any_cast". The > "argument type T in the function call" (as the standard puts it), is 'class > any'. The second bullet says "If T is a class type, its ... associated > namespaces are the namespaces in which its associated classes are defined" > which, in this case, is boost. Therefore namespace boost should be searched > for a template named "any_cast". I'm not as up-to-date with the standard as I'd have liked; that's why I said that I'm not sure whether this will work or not..) So I believe that Comeau is right. It usually is. :-) -- Peter Dimov Multi Media Ltd. Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2001/10/18563.php
CC-MAIN-2021-31
refinedweb
298
76.11
#include <wx/stream.h> This stream acts as a cache. It caches the bytes to be written to the specified output stream (See wxFilterOutputStream). The data is only written when the cache is full, when the buffered stream is destroyed or when calling SeekO(). This class may not be used without some other stream to write the data to (such as a file stream or a memory stream). Constructor using the provided buffer or default. Constructor allowing to specify the size of the buffer. This is just a more convenient alternative to creating a wxStreamBuffer of the given size and using the other overloaded constructor of this class. Calls Sync() and changes the stream position. Reimplemented from wxOutputStream.
https://docs.wxwidgets.org/3.1.2/classwx_buffered_output_stream.html
CC-MAIN-2019-09
refinedweb
118
66.84
Wikiversity:Colloquium/archives/August 2011 Contents - 1 Wikiversity - Lernen und Lehren translation anyone? - 2 Question in Arabic - 3 Collapse boxes working? - 4 How to contact other people? - 5 Wikiversity:Delegable proxy - 6 Undoing redirects/title renames - 7 From the Wikiversity content to its conflicts presentation at Wikimania - 8 how to improve my earing on the musical notes? - 9 Wikiversity:WMF outreach - 10 Language and Skills templates - 11 Wikiversity:Assembly - 12 Light and matter waves. - 13 Special:UncategorizedPages - 14 Template:JavaAPI and #replace function - 15 Wikiversity: 5 year birthday - 16 Mass moves of pages Wikiversity - Lernen und Lehren translation anyone? I think it would be useful if we could translate this into English. Is anyone prepared to help?Leutha 10:39, 1 August 2011 (UTC) - see + the talk page there, ----Erkan Yilmaz uses the Wikiversity:Chat + Identi.ca 15:42, 1 August 2011 (UTC) Excellent! Perhaps we can develop some discussion around this as an activity for Wikiversity Day 2011 coming up on 15 August? Question in Arabic مساء الخير .......... هل يوجد لدئ جامعتكم المحترمه دراسات عليا (ماجستير ادارة الاعمال؟ ولكم جزيل الشكر والتقدير باعلامي علئ هذا الايميل baghdad_tears20@yahoo.com Google translation: Good evening .......... Does your university Ldi respectable Graduate (Master of Business Administration? Thank you very much let me know and appreciation categorize this email Answer: Wikiversity does not offer degree courses. It is a place where free and open educational materials can be shared and developed. There are some business resources you may be interested to explore. Sincerely, James ويكي الجامعة لا تقدم دورات درجة. وهو المكان الذي يمكن تقاسم المواد التعليمية الحرة والمفتوحة والمتقدمة. هناك بعض الأعمال الموارد قد تكون مهتما لاستكشاف. بصدق، جيمس (Above emailed) -- Jtneill - Talk - c 13:08, 3 August 2011 (UTC) Collapse boxes working? Are collapse boxes still working on WV? (They aren't for me - but maybe that's because of browser upgrade). 02:50, 3 August 2011 (UTC) - Thanks, Abd. Yes, tested further and its broken for me too with Firefox Portable 5.0, IE 8.0, Chrome 12.0 on Windows XP. -- Jtneill - Talk - c 12:23, 3 August 2011 (UTC) - Something happened here to break it? Special:Contributions/Krinkle -- Jtneill - Talk - c 12:27, 3 August 2011 (UTC) - Could be. Now, how could Krinkle edit those pages? They are protected, and I don't see that he has the permissions. He's a developer on mediawikiwiki. But that wouldn't give him permissions here. I'll ask, in any case. The timing is about right. --Abd 00:48, 4 August 2011 (UTC) - Affected templates: {{Collapse top}}, {{Collapse box}}. Collapsible table class is unaffected. -- Jtneill - Talk - c 12:36, 3 August 2011 (UTC) - It works fine for me on Google Chrome 13.0.782.107, on Iceweasel 3.5.16 and on Epiphany 2.30.6. Helder 22:06, 3 August 2011 (UTC) - For me, I see the box, but it is not collapsed. It's visible with no action. Is that what you see? Or is there a collapse box, i.e., one line of title and an arrow to click on to expand it? --Abd 00:48, 4 August 2011 (UTC) - For me it is/was collapsed, but at the time I wrote my previous comment Darklama had alread restored the missing code, so perhaps I didn't had the chance to see the bug. Helder 13:35, 4 August 2011 (UTC) I restored part of some javascript code that Krinkle deleted when the content of a page was replaced. Browser cache might need to be cleared before it starts working again. -- darklama 02:14, 4 August 2011 (UTC) - Thanks, darkcode. Why was Krinkle able to edit that page in the first place? --SB_Johnny talk 10:43, 4 August 2011 (UTC) - (editconflict) - Hi, - Last week someone reported a bug to me about nested collapsible elements not working correctly on Wikiversity( When the outer collapsible box was expanded the inner ones would toggle the wrong way also). Several years ago, this bug also occurred on English Wikipedia, and was fixed in the mean time there. However, this wasn't the only bug fixed over the last years, so I answered his bug report by updating the script on Wikiversity (that was copied from Wikipedia a few years ago) to the current version documented on MediaWiki.org all at once (instead of only small pieces that may or may not be compatible anymore). The upgrade went good and the bug was fixed. - I accidentally overwrote a different script in MediaWiki:Navigation.js that was stored on the same page, I didn't know that there was another script on that page, my apologies and Thanks! to Darklama for restoring that! - @Abd: Pages in the MediaWiki-namespace are not and cannot be protected. It is a special namespace that is restricted to users with the 'editinterface' right. By default this means wiki sysops (see Special:ListGroupRights). Aside from local groups there are a few global groups that have this right (Stewards, Global sysops and Global interface). - Earlier this year the Wikimedia cluster has upgraded from MediaWiki 1.16 to 1.17 and with that upgrade came may significant changes, refactors and improvements to the JavaScript library and the default stylesheets. From the past 2-3 years of experience on Wikipedia and it's sister projects I got the impression that most wikis don't have the luxury of one (or multiple) programmers in the community that are also a sysop and are familiar with MediaWiki's JavaScript. Therefor I have requested and was granted the ability to edit the MediaWiki-namespace on Wikimedia wikis to discover problems that users may not be aware of during the upgrade (eg. bugs that only happen to Linux-users or bugs that happen with certain gadget combinations) and assist them in upgrading their scripts sooner rather than later. Wikiversity clearly has sufficient contributors in the JavaScript, so I'll stick to only fixing breaking changes and for the rest only make suggestions on talk pages that you can then pick up on (instead of me doing it). - Thanks again, Krinkle 11:05, 4 August 2011 (UTC) Thanks everyone for helping fix, maintain, and improve. All good now for me after clearing browser cache. -- Jtneill - Talk - c 11:37, 4 August 2011 (UTC) - Yes, as soon as I cleared my cache, it worked. I want to make it clear that I wasn't challenging Krinkle's right to edit, but only asking the question about rights. I'd looked and had apparently overlooked "interface editor." I thank Krinkle for helping us through this maintenance. That a minor error was made isn't a serious problem, particularly because it was quickly addressed. --Abd 17:23, 6 August 2011 (UTC) How to contact other people? --Yohomes 12:28, 6 August 2011 (UTC) How do I get in contact with other wikiversity people is there like a forum where everyone uses? I don't know what to do at all here to get in contact with other wikiversity people. --Yohomes 12:30, 6 August 2011 (UTC) I can't find anyone else on this wiki and how do I get in contact with others so they can help me learn? Is there a forum please send me a private message or something to help :(. - I have welcomed the user. - The Colloquium is one place where you can post a message that many will see. If you want to contact a specific user, you would use their Talk page. You may also send them email if you and they have email enabled. If you want help with respect to a specific topic, you can ask on the Talk page for the resource involved, but be patient. There might not be anyone watching that immediately. You may also look at the history ("View history" of a page) and see who has edited the page and when, and there is a link to users' talk pages there. I suggest not contacting a lot of users at once, be patient. Depending on the kind of help you want, there are also other pages you can use. You are welcome to ask me for specific help on my Talk page, User talk:Abd. --Abd 14:09, 6 August 2011 (UTC) Wikiversity:Delegable proxy A proposed mechanism for seeking and estimating broad consensus while still using ad-hoc participation, i.e., normal wiki process, has been documented, see Wikiversity:Delegable proxy. I'm engaged in a project to set this up and to use it to create a deliberative body, a Wikiversity:Assembly, to more efficiently advise decision-makers where broad participation is desirable, without necessarily assembling that participation (which, besides being difficult, can then can make discussions quite cumbersome). Please consider joining this project, see the Delegable Proxy page for instructions. Comments and suggestions and assistance are welcome, this is a community project. --Abd 22:44, 8 August 2011 (UTC) Undoing redirects/title renames Is there a way to undo other people going in and messing with titles via redirects? It is messing up subsequent pages and might be messing with templates? If this isn't resolved, I'll be forced to develop somewhere else... --Harriska2 22:47, 9 August 2011 (UTC) - Well, Harriska2, this is a collaborative project, so please be patient with other users. - Yes, there is a way to undo a page move. You have given us no examples, no clue as to what has happened. Any edit may be undone, usually. However you should always consider the reason given for the edit. If there is no reason given, you can usually undo it without that being a problem. If there are disagreements, there are ways to resolve them and experienced users who will help you. - To undo a move, look at history for the moved page. I finally found a page you had edited that had been moved. - Science for kindergarten was moved from Kindergarten elementary science in 2008. - Kindergarten elementary science was moved from your title, Elementary Science K, two months earlier, by a different user. - Normally, a move could just be undone. In page history, after the move record, there is an "undo" field, you can click on it and undo the move. However, if this is the move you are upset about, I've now deleted the intermediate redirects, and that simple process won't work (and it would have been complicated, there were really three moves because of a spelling error). But if you do want to move the page back, and nobody objects, I'll assist. (Non admins can undo moves, supposedly, but cannot move a page over a redirect that exists.) - Something is broken. I used a non-admin account to test undoing page moves and it didn't work. Don't know why. So ask for what you want. I can see with this example that your naming scheme was callously disregarded. But it was in 2008, Harriska2! (Maybe there is something else?) --Abd 00:17, 10 August 2011 (UTC) - It looks like if a page is moved twice, the last move can be undone by an ordinary user. Undo did not work for me, but a Move back did. However, more than that doesn't seem to work. --Abd 00:26, 10 August 2011 (UTC) From the Wikiversity content to its conflicts presentation at Wikimania Hi, everybody is welcome to comment (and fix grammar) of my presentation of Wikiversity at Wikimania in Haifa, which will take place in two days. I will show people what was created in Wikiversity during the last 5 years. I will talk also about some brokespining conflicts and on the end show the possible way of sorting Wikiversity content by content type, which was started here by user:McCormack back to 2008. They I will advertise a project, which have to sort Wikiversity content and customize some namespaces for different type of content. While the issue of conflicts which flow Wikiversity, that is an open question for me. So its here: From the Wikiversity content to its conflicts.--Juan de Vojníkov 15:51, 4 August 2011 (UTC) - So, what's the experience? Any new clues/feedback/suggestions from Haifa or elsewhere? ----Erkan Yilmaz uses the Wikiversity:Chat + Identi.ca 14:17, 12 August 2011 (UTC) how to improve my earing on the musical notes? --OrangeWxy 04:55, 12 August 2011 (UTC) - Could you please tell what you tried already? ----Erkan Yilmaz uses the Wikiversity:Chat + Identi.ca 14:18, 12 August 2011 (UTC) Wikiversity:WMF outreach Experts often (usually!) have some kind of conflict of interest in their fields, and frequently experts and COI editors are blocked on Wikipedia, for lots of reasons: they often don't understand how Wikipedia works, they imagine that their expertise should give them an advantage, or, perhaps an expert has a web site and promotes it and gets blocked as a spammer. However, on Wikiversity, we truly welcome experts. If there is some special conflict of interest, it should be declared, and experts should be very careful not to revert war, not to be uncivil; however, experts may freely develop educational resources here, and these resources may even, sometimes, be linked from Wikipedia articles. (If there are WV users who'd like to help with this outreach, by placing interwiki links -- theoretically encouraged by WP guidelines -- please let me know.) I help maintain the meta global spam blacklist, and came across this request. It occurred to me that the people who run that site may be experts in geneaological research, and perhaps they would like to help build geneaological research resources here. So I invited them, and I'd assist them in placing an appropriate link to their site here by whitelising as needed (or any sysop can do this, of course). It occurred to me that I've seen many unfortunate situations on Wikipedia where experts (and passionate amateurs) have been blocked and banned. What they really want to do, they could do here with positive results. Often, people want to discuss topics and that's actually prohibited on Wikipedia (background discussion is not considered relevant to article improvement), but it can be encouraged here, done properly. In all of these situations, we have an opportunity to recruit users for Wikiversity, to build deep resources. I'm excited about the possibilities, and I hope others will be as well. Accordingly, I'm starting Wikiversity:WMF outreach to coordinate and discuss interwiki outreach activities. --Abd 13:56, 17 August 2011 (UTC) - I have already seen some substantial results here from my own campaign to inform users who have run into trouble on other wikis to come here and contribute to resources. These users are often highly knowledgeable about the subject, and they ran into trouble because they did not understand the "encyclopedia" rules, which are very, very different from what obtains in academia (which can range all the way from very strict conformance to the requirements of peer review, to very informal presentations as conference papers or student essays or research reports with varying levels of requirements. If there have been new discoveries in a field, as an example, it would be "recentism" to incorporate them in an encyclopedia article, perhaps, but certainly these things can be covered and discussed in academia! And here! - I'm excited about the possibilities for the growth and function of Wikiversity, and this could also help the 'pedias, by shoving "discussion" of topics away from the 'pedias. People who have questions about the topic can find answers here, from people knowledgeable about it. As a Wikipedia editors, so many times I saw an editor slapped down for asking questions about the topic, or for explaining it to someone who had asked, instead of confining Talk page discussion to how to improve the article. Language and Skills templates A series of userboxes enabling users to indicate their skills in: - teaching - media production - press experience - project management have been transcluded from Outreach Wikimedia. Leutha 17:10, 21 August 2011 (UTC) Wikiversity:Assembly I have created the Wikiversity:Assembly community project. This is a possible method for finding deep consensus, enhanced by the networks of trust that are documented through Wikiversity:Delegable proxy. Please consider registering as a member of the Assembly on the Delegable proxy page, and please consider naming a proxy as being, ideally, the "most trustworthy" member of the community, the one you would most trust to "represent" you in a discussion where you are unable, for whatever reason, to participate yourself. It doesn't have to be perfect. Your proxy will not be "voting" for you, will not be binding you to anything. Then consider requesting that proxy to accept the designation (mutual acceptance is mutual consent to personal communication), and consider requesting the proxy to, himself or herself, name a proxy. If everyone did this, we would have a possibility of very high representation with very few participating Assembly members. Volunteers are needed to help develop and clerk processes. Please consider helping out. --Abd 16:44, 22 August 2011 (UTC) Light and matter waves. Can anyone please explain what exactly is light? Also, matter has dual nature and so, is matter to enery transformation possible? And can that Energy be in the form of light? --Configuregagan 04:47, 26 August 2011 (UTC) - Simple answer: No. Middle answer: wikt:Light. "Exact" answer: No. Everything that is, is light (or fields), so, what discrimination, exactly, would any explanation convey? But you can study Physics. Light is as light does. - Yes. - Yes, what else? - Okay, I'm using "light" to refer to the entire spectrum and configuration, all the way up to and including light trapped as matter. More normally, we consider things as light or matter, the former being free and moving at the "speed of light," the latter being confined. - At least that's my idea of it. --Abd 13:52, 26 August 2011 (UTC) Special:UncategorizedPages I've been working on the above pages for a while, but as I'm a relative newbie here, I thought I'd ask some advice. Where an obvious category for a page doesn't exist, I've been bold and created some, eg Category:boats, Category:tobacco, but I recently tried to create Category:artificial intelligence and was advised that it had been deleted as an "unnecessary cat" in 2009. Is there an existing hierarchical structure to categories I should be following? Given that User:Juan de Vojníkov/From the Wikiversity content to its conflicts at Wikimedia 2011 calls for "tidy up the mess = categorise pages by content type" I'd appreciate some guidance on this issue. Thanks Berek 10:12, 25 August 2011 (UTC) - I haven't checked thoroughly, but presumably then the category was not used. Categories that aren't used are often deleted, but if you have a use for it, you may go ahead and create it. --Abd 13:55, 26 August 2011 (UTC) - You may also be interested in [[Category:Uncategorized pages]]. These don't show up in Special:UncategorizedPages because they're categorized by {{Uncategorized}}. --Draicone (talk) 14:58, 26 August 2011 (UTC) - May I suggest, then, that the categories Category:Uncategorized and Category:Uncategorized pages are not needed? It's just confusing and, in fact, self-contradictory! And adding the template is adding work with no value (to add the template and later to remove it). (It's like "this page has no content," only without the redeeming value of that text on a page (it's usually there to indicate that a page is deliberately -- and otherwise -- blank). (Draicone, you might want to more simply disable a category or template with an initial colon, as with Template:Uncategorized, which still allows someone to actually look at the category or template.) I can see having a template for pages that might need further categorization. But not that have none. --Abd 15:59, 26 August 2011 (UTC) Template:JavaAPI and #replace function The Template:JavaAPI would have use for the #replace: function contained in the StringFunction extension. --Bernhard Fastenrath 09:44, 29 August 2011 (UTC) Wikiversity: 5 year birthday After the enormous feedback from 2 months ago a short reminder: less than 3 days left for the party, ----Erkan Yilmaz uses the Wikiversity:Chat + Identi.ca 14:13, 12 August 2011 (UTC) - Hmm. Does Wikiversity have site banners? Maybe it would be good to let readers know about and appreciate this milestone. :) --User:Moonriddengirl/Mdennis (WMF) 20:46, 12 August 2011 (UTC) - We could set up a sitenotice.... I'd be happy to help with that. Philippe (WMF) 21:11, 12 August 2011 (UTC) Business up front, party in the back.--Gaon Abhinava 02:16, 31 August 2011 (UTC) Mass moves of pages Custodians have a move option to move all subpages with a page. Howard Community College has been creating a lot of pages for a general engineering course, and I wanted to try moving courses under HCC, because many scattered mainspace pages were being created with highly specialized names. I moved a page that had 37 subpages, not noticing that this would create some redundant pagenames, i.e, Howard Community College/.../Howard Community College/... Then I could not find a way to undo a mass page renaming. The problem is the redirects. I'd have to delete all the redirects first. I'm discussing the naming scheme with HCC with a teacher from the school. Meanwhile, any ideas about undoing page moves, or is this basically a MediaWiki bug? (i.e., if making a mass move and leaving redirects, it can't be undone without acting on each individual page in some way.) Lesson for me for the future: don't make mass moves without discussion first. I'd thought this would be simple to undo. Not. I wanted to leave redirects in case someone had added links, and checking many subpages for links... not fun. --Abd 19:24, 31 August 2011 (UTC) - I think support for mass page moves was added as a quick hack job. No support for undoing mass page moves exist yet. You could report it as a bug or suggest it as a feature improvement. -- darklama 20:04, 31 August 2011 (UTC) - The interface should warn about the undoability of mass moves. I'll check on that. --Abd 21:26, 3 September 2011 (UTC) - Ugh. Move-subpages is poorly documented on the mediawiki wiki. There doesn't appear to be a MediaWiki page that controls the message. Any clues? --Abd 16:27, 4 September 2011 (UTC)
https://en.wikiversity.org/wiki/Wikiversity:Colloquium/archives/August_2011
CC-MAIN-2019-43
refinedweb
3,763
64.1
Messaging with RabbitMQ and .NET review part 4: one way messaging with a basic consumer August 8, 2016 3 Comments Introduction In the previous post we looked at the RabbitMq .NET client. The client is a library that can be downloaded from NuGet and which allows us to work with RabbitMq messages in our .NET projects in an object-oriented way. In particular we saw how to create an exchange, a queue and a binding in code. We also successfully sent a message to the queue we created in a simple .NET console application. We also discussed the notion of durability whereby we can make all resources in RabbitMq fault tolerant so that they survive a server restart. In this post we’ll see how to consume one-way direct messages in code. We started working on a demo console application in the previous post. We’ll be working in it throughout this series so you can open it now. At this point we have one console app in the project which creates the resources for messaging and also sends a message to a queue. One-way messages A one-way message is a kind of message exchange pattern (MEP). This is the simplest MEP type: a message is sent to the broker which is then processed by the receiver. Add a new console application called RabbitMq.OneWayMessage.Receiver to our demo project. Add the same RabbitMq .NET client package from NuGet to it as we did previously. The little code we created in the previous post is actually a one-way message sender with its usage of the BasicPublish method. In the original series we used the QueueingBasicConsumer class to process messages from a queue. However, it is now deprecated and been replaced by DefaultBasicConsumer. It is a basic implementation of the IBasicConsumer interface which handles functions such as message delivery and cancellation. The recommended solution at this point in time is to derive from this class and override its HandleBasicDeliver method. So let’s do that! Add a new class called OneWayMessageReceiver to RabbitMq.OneWayMessage.Receiver. Here’s the skeleton which we’ll fill in in a short time: using RabbitMQ.Client; namespace RabbitMq.OneWayMessage.Receiver { public class OneWayMessageReceiver : DefaultBasicConsumer { private readonly IModel _channel; public OneWayMessageReceiver(IModel channel) { _channel = channel; } public override void HandleBasicDeliver(string consumerTag, ulong deliveryTag, bool redelivered, string exchange, string routingKey, IBasicProperties properties, byte[] body) { } } } I know that we’ll need an IModel object later on for the message acknowledgement. That will become clearer soon. Before we do anything else in this code let’s add the code that will hook up OneWayMessageReceiver with the queue. Add the following bit of code into the Main method of the Program class in RabbitMq.OneWayMessage.Receiver: using RabbitMQ.Client; namespace RabbitMq.OneWayMessage.Receiver { class Program { static void Main(string[] args) { ReceiveSingleOneWayMessage(); } private static void ReceiveSingleOneWayMessage() {); DefaultBasicConsumer basicConsumer = new OneWayMessageReceiver(channel); channel.BasicConsume("my.first.queue", false, basicConsumer); } } } The first section in ReceiveSingleOneWayMessage where we set up the RabbitMq connection and channel is identical to what we had in the publisher previously. I know that this is some serious code duplication but let’s not worry about that for now. This series is not about clean code and layered applications so it’s up to you to organise all these code examples into some well structured application as you develop your messaging project. The last three lines of code are new. The BasicQos function, where QOS stands for quality of service, sets up the basic behaviour of message handling. The parameters mean that we require one message at a time and we don’t want to process any additional messages until the actual one has been processed. You can use these parameters to receive messages in batches. The first integer parameter, i.e. the prefetch size, sets the maximum size of for the messages fetched from the queue where 0 means there is no upper limit. The second integer, prefetch count, is the number of messages to be fetched from the queue at a time. E.g. if it’s set to 5 then if there are 20 messages in the queue then 5 of them will be delivered to the consumer(s) in one batch. The boolean “global” parameter is set to false which means that the prefetch limits are valid for the current channel only, not for the entire connection. We then declare a new one way message receiver that we derived from DefaultBasicConsumer. We finally call the channel’s BasicConsume function. The first parameter is the queue name to be monitored. The second is a boolean which if set to false then we require an acknowledgement from the receiver. Why “false” if we do require an acknowledgement??? The parameter is called “noAck”, i.e. “no acknowledgement” where true means that we do not need any acknowledgement and this must be negated with a false. Lastly we pass in our basic consumer. The implementation of the HandleBasicDeliver function of DefaultBasicConsumer is not too exciting actually since we’re not developing a business application. We simply output some parameters to the debug window: public override void HandleBasicDeliver(string consumerTag, ulong deliveryTag, bool redelivered, string exchange, string routingKey, IBasicProperties properties, byte[] body) { Console.WriteLine("Message received by the consumer. Check the debug window for details."); Debug.WriteLine(string.Concat("Message received from the exchange ", exchange)); Debug.WriteLine(string.Concat("Content type: ", properties.ContentType)); Debug.WriteLine(string.Concat("Consumer tag: ", consumerTag)); Debug.WriteLine(string.Concat("Delivery tag: ", deliveryTag)); Debug.WriteLine(string.Concat("Message: ", Encoding.UTF8.GetString(body))); _channel.BasicAck(deliveryTag, false); } The message body is held by the “body” parameter as a byte array. The “properties” parameter is the same IBasicProperties object we saw when publishing a message to the queue. The consumer can read the message properties like the MIME type, the correlation ID, the message ID and a range of other properties that the publisher may have specified. Your code logic can be tweaked based on those parameters. The correlation ID can be used to correlate messages. E.g. if a new order is placed then various systems may want to know about it: accounting, delivery, production, supply planning etc., and they will each handle the new order in some way. The correlation ID from the publisher can be used to check what happened to a particular order in those various systems. The delivery tag is an integer and is used for acknowledging a message. When RabbitMq has received the acknowledgement then the message is deleted from the queue. This tag usually indicates the position of the message in the queue: 1 is the first message, 2 is the second message etc. according to FIFO. The consumer tag is a unique ID on the message such as “amq.ctag-qCDfYIYQEpGqvAY7t-bhCQ”. We’ll come back to the redelivered argument in a short bit. Set a breakpoint in the beginning of HandleBasicDeliver. Run the RabbitMq.OneWayMessage.Receiver application in Visual Studio. If you’ve followed along the series so far and published a message to RabbitMq in the previous post then code execution should stop at the breakpoint meaning there’s a message for our consumer. As you step through the code you should see some debug messages similar to the following: Message received from the exchange my.first.exchange Content type: text/plain Consumer tag: amq.ctag-sr_eLwVpAv8N75fUMfAscA Delivery tag: 1 Message: This is a message from the RabbitMq .NET driver Also, if you inspect the redelivered property it should be true. The reason is that we actually viewed the message in the management GUI in the previous post so it’s already been handled once but not yet acknowledged by any receiver. If you re-run the publisher code with some modified message and immediately execute the consumer application then “redelivered” should be false. We finally use the channel to acknowledge the message. We supply the delivery tag and a boolean parameter. If it’s set to false then the acknowledgement is only for this message and not for all messages in the queue. Worker queues Before we finish this post I want to mention another MEP that is very similar to one-way messages and which can be easily demonstrated with the minimal code we have now. In the worker queues MEP a message is sent by the publisher. There will be many listeners waiting for messages from the same queue. However, those listeners compete to receive the message and only one of them will receive it. The purpose is that if an application is expecting to receive a large load of messages then it can create different threads/processes to process those messages. The benefit is better scalability. We can simulate this MEP by starting two or more instances of RabbitMq.OneWayMessage.Receiver. If you’re not sure how to do it then right-click the project name in VS, select Debug in the context menu and then click Start new instance. Do this process twice so that you have 2 listeners up an running. Then start the publisher multiple times using the same technique so that several messages are published to the queue. You should see that the consumers take turn in receiving the messages in a round-robin fashion: We’re done for now. We’ll continue with a different, event based way of handling messages in the next post. View the list of posts on Messaging here. Hi, By far this is the most extensive and thorough instruction over the internet regarding RabbitMQ. Thanks a lot!! While running the sample above, I’m getting an unclear error: An unhandled exception of type ‘RabbitMQ.Client.Exceptions.AlreadyClosedException’ occurred in RabbitMQ.Client.dll Additional information: Already closed: The AMQP operation was interrupted: AMQP close-reason, initiated by Peer, code=404, text=”NOT_FOUND – no queue ‘my.first.queue’ in vhost ‘Replication'”, classId=60, methodId=20, cause= While I can see on the console the queue and the message as was added on the previous post. I know it is an old post but I hope you can help me with this exception as it blocks me on a very basic stage… The versions I’m using are the latest: Erlang OTP 20.1 rabbitmq-server-3.6.14 RabbitMQ.Client 5.0.1 and .Net 4.6.1 on VS2015 Thanks in advanced! Hi, Me again. I’ve played around with the Exchange and Queue names and all of a sudden all started to work. Not sure what was the problem beforehand but now all works. You can just delete these two posts if you like. Thanks again for amazing series of posts on RabbitMQ! Alon Sir after creating this console listener do we want to schedule it in the task windows scheduler
https://dotnetcodr.com/2016/08/08/messaging-with-rabbitmq-and-net-review-part-4-one-way-messaging-with-a-basic-consumer/
CC-MAIN-2020-10
refinedweb
1,799
56.76
. In this chapter, we make explicit use of the basic information described in chapter two, in particular the how to display a video image and some of the ideas in chapter 5 on converting between co-ordinate systems. One of the big attractions of the Kinect is that it not only provides raw video and depth data, but also the way that it processes it to produce player indexes - see chapter 4 - Chapter 2, so if you need detailed explanations of how it all works read that chapter. Microsoft.Kinect.dll. and add: using Microsoft.Kinect; using Microsoft.Kinect; To the start of the program. In the Form's constructor we create a Runtime object so that we can use the Kinect: public Form1(){ InitializeComponent(); sensor = KinectSensor.KinectSensors[0];} The sensor variable is global allowing us to get a the Kinect from anywhere in the program - not good design but simpler for an example. KinectSensor sensor; Next you have to initialize it to use video and the depth camera and to use SkeletalTracking :();} When the FramesReady event handler is called both the depth and the video frame are ready to be processed: void FramesReady(object sender, AllFramesReadyEventArgs e){ First we retrive the video data. The idea is that we are going to mark the location of the head on the video data as the tracking follows the player around the frame. ColorImageFrame VFrame = e.OpenColorImageFrame();if (VFrame == null) return;byte[] pixeldata = new byte[VFrame.PixelDataLength]; We are going to want to draw a cross on the video data. In the previous chapters whatever graphics facilities the framework you are using provides. The problem is that there is a split between Windows Forms and WPF. For this example we are going to use Windows Forms and the GDI because it is closer to the same facility in C++. In the next chapter we will look at using WPF graphics.
http://i-programmer.info/ebooks/practical-windows-kinect-in-c/3911-kinect-sdk-1-skeletons.html
CC-MAIN-2013-48
refinedweb
318
60.65
Programming Programming Questions? Ask a Programmer for Answers ASAP Hello, My code below is meant to only print "YES" when it finds a row that contains all ones in java but when it finds a column that contains all ones it still prints "YES"! How can I fix my code below so that it only prints "YES" when it only finds a row all equal to 1? Many thanks, Samia import java.util.*; public class fixst{ public static void main(String [] args) { int total =0; int [][] a = {{1,7,2},{7,1,8}}; //2D ARRAY boolean yes=false; //TO CHECK IF THERE'S A ROW IN 2D ARRAY THAT HAS ALL 1s for(int i = 0;i<a.length; i ++) //loops through rows { for(int j = 0; j<a[i].length; j ++) //loops through columns { int num = a[i][j];if(num == 1) //everytime number is ***** adds to total { total++; }if (total==a[0].length) //if total equals to rows length it means all elements in a row are equal to 1{ yes = true;}}} if(!yes) { System.out.println("NO"); } else { System.out.println("YES elements in a row are all equa to 1! "); } }} Thanks :) please as soon as possible as i've got a deadline at 11:45pm tonight. Also if possible and you have time, I have one more question which i'm really struggling with. I can pay you more if you can please write the following program in java and explain to me how it works... Write a program that prints “YES” if in each row of A, all the elements are distinct and “NO” otherwise. (Hint: First write a function that takes as input a one-dimensional array and checks if all elements in this array are distinct. Then, apply this function to each row of a matrix (treating this row as a one dimensioal array). Print “YES” if and only if the function returns TRUE for each row. Only when ALL ROWS have distinct values please. Sorry copied the code you sent me into Bluej and I got this error for a[j] which says int[] can not be converted to int! Also I cannot do skype tonight but I can on another day when your free. For the meantime can you please clearly comment on the code. I'm afraid i'm still having the same problem with my code. My email is***@******.*** Yes I did. Thank you I will shortly provide you with a ratting. It finally fully works now :) Thank you it works. I understand everything but this: //set cannot have duplicates Set mySet = new HashSet(); //add each element in array to set for(int elem:row) mySet.add(elem); I've never seen this!
https://www.justanswer.co.uk/computer-programming/9dqt7-do-know-check-elements-rows.html
CC-MAIN-2018-17
refinedweb
454
81.93
The Storage Team Blog about file services and storage features in Windows and Windows Server. Thanks to Shobana Balakrishnan, Richard Chinn, and Brian Collins for contributing to this blog. OverviewAnti-virus applications have caused interoperability problems with file replication in the past, namely with NTFRS (File Replication service). In particular, excessive replication can be triggered by poorly behaved anti-virus applications as their scanning activities are interpreted as file changes needing replication. DFS Replication (DFSR) relies on the same file system facilities as NTFRS for detecting file changes, so it is subject to similar problems. DFSR’s new design may make it more robust and tolerant of such applications at the cost of additional processing, but full interoperability must be tested. The tests should cover the following areas. The following features of the anti-virus application should be covered. Note this blog simply provides recommendations and guidelines for testing. Simply running all theses tests will not guarantee a given anti-virus program’s interoperability with DFSR. Test EnvironmentSet up two replication partners, one with the anti-virus product of interest and one without any anti-virus software. Both partners should have a scratch volume that is only used for replicated folders. This will minimize noise in the tests. Tests Excessive ReplicationExcessive replication is caused by programs making no effective changes to files yet causing changes to be introduced in the USN journal. DFSR sees these changes and is able to suppress some of them as it realizes that file hashes are unchanged. This is in contrast to NTFRS which would replicate such changes. Still, in the DFSR case, it is best to not have spurious changes being introduced into the system as it will increase the load on the server. To monitor USN activity, use PerfMon to show the USN Journal Records Accepted performance counter under the DFS Replication Service Volumes object. If DFSR accepts a USN journal record, then this is a file change that is eligible for replication. If you like, you may also add USN Journal Records Read; this reflects the USN journal records that DFSR has read on the given volume. Changes outside the replicated folder are not accepted. It is easiest to see the numbers if PerfMon is configured to display a report view. An alternate way to monitor USN activity is to monitor the DFSR debug logs with a utility such as tail.exe. Using tail -f on the last debug log will show the real-time debug logs as written by DFSR. Log messages with USNC are those related to the USN consumer. You must beware of the logs wrapping to the next log file. To enable debug logs, run the following WMI command on the members. wmic /namespace:\\root\microsoftdfs path DfsrMachineConfig set EnableDebugLog=true,DebugLogSeverity=5,MaxDebugLogFiles=10000 Here is the test procedure. 1. Set up replication between M1 and M2 for a replicated folder. 2. Configure M1’s replicated folder for real-time monitoring. 3. Set up USN journal monitoring using the method of your choice. 4. Populate the folder with various files of interest including executables and documents. 5. Ensure DFSR has synced the two folders and backlogs are zero (e.g. run a health report from DfsMgmt.msc or use DfsrDiag.exe with the backlog option). 6. Perform an on-demand scan on M1. 7. Verify no USN journal records are accepted on M1. 8. Try accessing files / running programs on M1. 9. Verify no USN journal records are accepted on M1. 10. Make all the files on M1 read-only using attrib.exe or the Explorer. This will cause USN journal activity. Let DFSR sync and verify the backlog drops to zero. 11. Perform an on-demand scan on M1. 12. Verify no USN journal records are accepted on M1. 13. Copy a file from another volume, preferably something excluded from anti-virus monitoring, into the replicated folder. 14. Verify there is only one USN record accepted by DFSR. 15. Move a file from the same volume, preferably from a folder that is excluded from anti-virus monitoring, into the replicated folder. 16. Verify there is only one USN record accepted by DFSR. Interfering with ReplicationAnti-virus programs have the ability to delete or move an infected file to a special quarantine area. Depending on how the infected file is detected and how the deletion or move is done, this may cause DFSR to become permanently backlogged and repeatedly attempt to download and install the file into the replicated folder. Anti-virus programs with good interoperability are able to delete, clean, or quarantine the file on one member, and have the changed file replicate normally. Sometimes this will require setting an exception filter on the entire DfsrPrivate folder. Testing with infected files is facilitated by using a virus test file called eicar.com from. 2. Verify replication between M1 and M2. 3. Configure real-time scanning on M1. Configure it to quarantine or delete. 4. Copy the infected file into the replicated folder on M2 and monitor M1, M2, and the backlogs between the two servers in both directions. There are a few things that can happen, so here are some to watch out for. 5. The above tests should be repeated using the clean functionality. Local and Remote AccessThere may be subtle differences when a file is accessed over a share versus to locally on the server itself. Since DFSR is used between file servers, it will most likely be the case that users will be accessing files over shares. As a result, it is important to try the above tests over shares as well as locally. Similarly, client-side anti-virus applications that monitor remote shares as well as applications that scan shares should also be tried if applicable to your scenario. RecommendationsProblems will generally be minimized if infected files are never allowed into the replicated folders, especially when one member sees a file as infected but another member does not. To minimize this, you should do the following. Also, anti-virus application behavior will vary from version to version and operating system to operating system. It is important to perform the testing procedure for each new version that is considered for deployment. Here are some tests you can use to test Interop of additional products: Backup 1. Create replicated folder, start DFSR, replicate some files a. Verify replication works 2. Run backup application a. Verify no errors in DFSR eventlog b. Verify replication still works after backup c. Verify no lingering backlogs d. Verify backup did not trigger unexpected replication 3. Delete some data, then restore backed-up files a. Verify no errors in DFSR eventlog b. Verify replication still works after restore c. Verify no lingering backlogs d. Verify restored files are replicated Encryption, Quotas, Defrag, Monitoring Test 1: Creating a replicated folder on machines already configured w/ vendor’s product 1. Install product on test server(s) and configure as needed so it will impact the to-be-created replicated folder 2. Create replicated folder with existing data on some or all members, start DFSR, replicate some files a. Verify all members sync up with each other b.Verify no errors in DFSR eventlog c.Verify no extra replication d. Verify no lingering backlogs 3. Play with the replicated data (create new files, modify files, delete files, etc.) b. Verify the file modifications replicate c. Verify no extra replication 4. If application is capable of running some sort of scan (like an AV scan), run it a. Verify no errors in DFSR eventlog b. Verify no unexpected extra replication Test 2: Configure vendor’s product on machines already hosting replicated folder 1. Create replicated folder with existing data on some or all members, start DFSR, replicate some files 2. Install product on test server(s) and configure as needed so it will impact the replicate folder a. Verify no errors in the DFSR eventlog b. Verify no unexpected extra replication c. Verify replication still works after product is installed & active PingBack from
http://blogs.technet.com/b/filecab/archive/2006/05/01/426926.aspx
CC-MAIN-2013-48
refinedweb
1,340
58.18
Revision history for Class::Accessor::Grouped. 0.10012 2014-10-05 21:22 (UTC) - Fix tests tickling deficient threads on perl 5.10.0 0.10011 2014-09-26 11:24 (UTC) - Soft-depend on newer (bugfixed and *simpler*) Class::XSAccessor 1.19 - More robust threading tests 0.10010 2013-04-24 02:58 (UTC) - Fix bug with identically-named 'simple' accessors in different classes set to access *differently named fields* getting their field access mixed up - Fix subtle pessimization when having identically-named accessors in different classes leads to 'simple' implementations not being replaced by Class::XSAccessor where appropriate 0.10009 2012-11-15 18:51 (UTC) - Stop leaking extra methods into the inheritance chain - there are plenty already 0.10008 2012-11-15 09:48 (UTC) - Allow disabling of accessor name checking introduced in 0.10007 - Pass tests if Class::XSAccessor is available but Sub::Name isn't 0.10007 2012-11-08 11:54 (UTC) - Disable tests on perls where Class::XSAccessor emits broken error messages (RT#74883, RT#80519) - Drop minimum perl to 5.6 (from 5.6.2) - Switch all module loading to Module::Runtime and lose dependency on Class::Inspector - Fix stupid mistake causing double-require of Sub::Name when Class::XSAccessor is not available (RT#80657) - Simplify superclass traversal done by the 'inherited' group type - Fix incorrect quoting of unusual hash keys (fieldnames) - Depend on newer bugfixed Class::XSAccessor 1.15 - Improve text of ro/wo violation exceptions - Sanity-check accessor names for well-formedness (qr/[A-Z_a-z][0-9A-Z_a-z]*/) 0.10006 2011-12-30 03:52 (UTC) - Silence warnings resulting from incomplete can() overrides hiding get/set_simple methods 0.10005 2011-12-26 12:43 (UTC) - Depend on newer bugfixed Class::XSAccessor - Repack with correct metadata (RT#73100) 0.10004 2011-11-28 21:20 (UTC) - No longer leak internal __CAG* methods into the inheritable namespace 0.10003 2011-05-03 00:15 (UTC) - Only require MRO::Compat for older perls - Add SYNOPSIS - Add examples for methods that get used most often 0.10002 Sun Dec 19 05:23:44 2010 - Fix grave bug of XS-enabled simple accessors clobbering an existing 'around' overlay installed in the same method slot - Require bugfixed XSAccessor, remove Win32 caveat 0.10001 Sun Dec 12 03:17:05 2010 - Fix an ActiveState Win32 incompatibility - Fix spurious method re-invocation warnings after Class::Unload 0.10000 Sat Nov 27 17:51:04 2010 - Fix perl 5.6 failures - Add test-time deferred coderef reinvocation checks - Another minor (8%) speedup 0.09009 Fri Nov 26 01:31:56 2010 - Major cleanup and optimization of code (evaled coderef sharing) - Module can now operate in PurePerl environments with 100% compatibility (including proper naming of generated coderefs) 0.09008 Sun Oct 11 07:41:56 2010 - Put back a private undocumented method that the DBIC-CDBI compat layer relies on :( - Fix corner case segfaults with C::XSA and old 5.8 perls 0.09007 Sat Oct 9 10:22:56 2010 (DELETED) - Fix corner case when get/set_simple overrides are circumvented iff Class::XSAccessor is present 0.09006 Fri Sep 10 23:55:00 2010 - Fix bugs in ro/wo accessor generation when XSAccessor is being used - Better Class::XSAccessor usage control - introducing $ENV{CAG_USE_XS} and $Class::Accessor::Grouped::USE_XS 0.09005 Wed Sep 1 04:00:00 2010 - Again, remove Class::XSAccessor for Win32 sine it still breaks) 0.09003 Fri Apr 23 23:00:19 2010 - use Class::XSAccessor if available for 'simple' accessors, except on MSWin32, with documentation 0.09002 Tue Oct 20 23:16:28 2009 - removing Class::XSAccessor usage for now 0.09001 Thu Oct 1 21:48:06 2009 - remove optional dep from Makefile.PL 0.09000 Sun Aug 23 20:08:09 2009 - release 0.08999_01 Tue July 7 22:06:21 2009 - Make _mk_group_accessors name the closures installed for Moose compat - Use Class::XSAccessor if available RT#45577 (Andy Grundman) 0.08003 Sat Mar 21 9:27:24 2009 - Fixed set_inherited under C3::Componentised: RT#43702, RIBASUSHI code for pure speed while fixing performance issue when assigning @_ under Perl 5.10.0 0.07000 - Altered get_inherited to return undef rather than () when no value set for Class::Data::(Inheritable|Accessor) compatiblity - Fixed spelling test error - Added WriteAll/DIST/PREOP for README 0.06000 Fri May 11 22:00:26 2007 - get_super_paths now uses mro::get_linear_isa to DTRT under C3 0.05002 Fri May 11 20:46:16 2007 - killed Class::Inspector->installed warnings 0.05001 Thur May 10 20:55:11 2007 - set_component_class now only dies if the specified class is a installed/installable class and fails to load it. 0.05000 Tue May 08 19:42:33 2007 - Added get/set_component_class 0 04000 Sat May 05 21:17:23 2007 - Converted to Module::Install - Added culterific tests/TEST_AUTHOR - Converted to distro friendly version number 0.03 2006-11-07 21:33::35 - big speedup for get_inherited - get_inherited now checks the current class first before calculating super_path - get_inherited now caches super_path results 0.02 2006-06-26 19:23:13 - Added return statement to end of get_inherited - Fixed pod NAME 0.01 2006-06-26 17:38:23 - initial release
https://metacpan.org/changes/distribution/Class-Accessor-Grouped
CC-MAIN-2015-35
refinedweb
871
54.22
Hi, I have a cube, let's call it player, under that i have a procedurally generated plain, the palyer is going to move or rather float above and along that plain, I want to: A) get the vertices around the cube that are in the radius of the player. now i have achived that by looping through all vertices in that plain but that massivly cuts performance. i want to be able to get the vertices that are in the radius with somthing like physics.overlapsphere without having to loop through all the vertices, this obviusly doesn't work since overlapsphere ruturns a collider array and i want vertices which are a verctor3. B) raise those vertices on the y axis relative to the players position (the closer the vertex is to the player the higher it is), now i have also gotten this to work but its not as nice and smooth as i want it to be, the vertices just lerp the Y axis to 3 if they are in the radius, and if not the don't move at all. i want it to more dependent on more of where the player is rather than if its in the radius, If you get what i mean. physics.overlapsphere Here is my current code: using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; using UnityEngine.UIElements; [RequireComponent(typeof(MeshFilter))] public class MeshGenerator : MonoBehaviour { //player's refrence public Transform player; //minimum distance for the vertex from the player to be affected and raised up public float minDistance; //limit for the vertices on the Y axis public float meshOffset; //mesh generation stuff Mesh mesh; Vector3[] vertices; int[] triangles; public int xSize = 20; public int zSize = 20; void Start() { mesh = new Mesh(); GetComponent<MeshFilter>().mesh = mesh; CreateShape(); UpdateMesh(); } void Update() { MoveVertices(); } //Basically creating a plain at runtime to have a refrence to the vertices void CreateShape() { vertices = new Vector3[(xSize + 1) * (zSize + 1)]; for (int i = 0, z = 0; z <= zSize; z++) { for (int x = 0; x <= xSize; x++) { vertices[i] = new Vector3(x, 0, z); i++; } } triangles = new int[xSize * zSize * 6]; int vert = 0; int tris = 0; for (int z = 0; z < zSize; z++) { for (int x = 0; x < xSize; x++) { triangles[tris + 0] = vert + 0; triangles[tris + 1] = vert + xSize + 1; triangles[tris + 2] = vert + 1; triangles[tris + 3] = vert + 1; triangles[tris + 4] = vert + xSize + 1; triangles[tris + 5] = vert + xSize + 2; vert++; tris += 6; } vert++; } } //updating the meshes vertices and triangles and recalculating lighting on the surface of it void UpdateMesh() { mesh.Clear(); mesh.vertices = vertices; mesh.triangles = triangles; mesh.RecalculateNormals(); } //Using the players refrence to get his pos and looping through the vertices array to find which vertices are in the redius of the player // This is the part that i am not certain of void MoveVertices() { for (int i = 0; i < vertices.Length; i++) { float distance = Mathf.Sqrt((player.position - vertices[i]).sqrMagnitude); if (distance < minDistance) { vertices[i].y = Mathf.Lerp(vertices[i].y, meshOffset, Time.deltaTime * distance); UpdateMesh(); }else { vertices[i].y = Mathf.Lerp(vertices[i].y, 0, Time.deltaTime * distance); UpdateMesh(); } } } private void OnDrawGizmos() { if (vertices == null) return; for (int i = 0; i < vertices.Length; i++) { Gizmos.DrawSphere(vertices[i], 0.1f); Gizmos.color = Color.red; } } } for visualization, i am basically triying to mimic geometry wars meshs and how they react to objects positions and what's happening on the battle field As always, any help is appreciated Thanks in advance! Answer by Bunny83 · May 14 at 01:59 PM Well since your vertices are at a known location in your vertices array you can directly calculate backwards to find the indices of the vertices around you. This of course requires you to have your parameters for your plane generation at hand. From your code it looks like you just create the vertices at integer locations. Keep in mind that vertices are specified in local space. So it's generally simpler to work completely in local space. That means you would first convert your "player's" position into local space of your plane object. Now we have everything in the same coordinate space. Since the vertices are located at integer positions we can simply floor the player position to get the integer offsets in each axis. To get the index of the "lower left" vertex next to the player position you just do Vector3 playerPos = planeObj.transform.InverseTransformPoint(player.position); int x = Mathf.FloorToInt(playerPos.x); int z = Mathf.FloorToInt(playerPos.z); int index = x + y * (xSize + 1); NOTE: this code has no bound checking / clamping. So this breaks down as soon as the "player" gets off your plane. Of course now that you have the closest vertex index you can simply walk in both directions around that vertex. For example if you need a 7x7 area around your lower vertex you can simply use a nested for loop for (int dy = -range; dy <= range; dy++) { int ty = y + dy; if (ty < 0 || ty > ySize) // out of bounds continue; for (int dx = -range; dx <= range; dx++) { int tx = x + dx; if (tx < 0 || tx > xSize) // out of bounds continue; int index = tx + ty * (xSize+1); // check the vertex at "index" here } } Note that you really shouldn't call your UpdateMesh method every iteration. Call it once at the end of your loop. Finally note that you don't move your vertex "relatively" but you slowly move it to an absolute position. In your case the value of "meshOffset" is used as a "target value" to move towards. Your usage of Time.deltaTime and distance looks a bit weird to me. You essentially wil move the vertices the furtherst away from the player the most while those closest to the player would get almost no effect at all. All points outside your "minDistance" (which seems more like a maxDistance ^^) would actually be moved towards the absolute position of "0". I'm not sure if that's what you wanted to do but the result would look really strange. At the boundary of your "minDistance" you get a sharp drop from your meshOffset height down to 0. Though since your question was focused on how to cut down the number of vertices you have to process I think the question is answered ^^. If you need further help (with whatever you're actually doing), please ask a seperate question (you can refer to this one with a link) and be more clear what this is all about. To me it looks a bit like a messed up terrain editor tool ^^. But hey, we can only judge based on what we actually know from the description. So.... first thanks for your help with the " cutting down verices processed " part. But you don't seem like you got what i was hoping you'd get, and that totally my fault, (just to clarify I wrote this script before going to sleep so you now know why the veriables are named this wierdly). so about the penultimate paragraph: 1 - meshOffset was absolutely used as a terget i just miss named it 2 - usage of the time.deltatime is absolutely not accepable in this community, but i was experamenting with it in hopes of maybe...just maybe get it to work in the way i wanted 3 - You essentially wil move the vertices the furtherst away from the player the most while those closest to the player would get almost no effect at all, you got this part the wrong way around, furthest = almost no effect while the closest have the most effect (Hight) almost like the vertices get attracted to the player 4 - "minDistance" this should've been max distance or somthing like radius like you said 5 - I really get that sharp difference in hight between vertices which isn. Change vertex position not working? 2 Answers How to Avoid splitting Normals on Geometry with blendshapes 0 Answers Reload meshes with readable = true? 0 Answers Edit SkinnedMesh with vertices 0 Answers Some triangles are black on a mesh generated by script 1 Answer
https://answers.unity.com/questions/1730308/moving-vertices-dynamicly-relative-to-other-object.html
CC-MAIN-2020-45
refinedweb
1,348
57.81
im currently developing a project which requires to encrypt message in java platform and decrypt in asp.net. In java, i was asked to use the code below to encrypt the message. But i found out i could not decrypt it as i do not know how to get the key, IV fom java. By the way, im using AES decryption method from. import java.security.*; import javax.crypto.*; import javax.crypto.spec.*; import java.io.*; /** * This program generates a AES key, retrieves its raw bytes, and * then reinstantiates a AES key from the key bytes. * The reinstantiated key is used to initialize a AES cipher for * encryption and decryption. */ public class AES { /** * Turns array of bytes into string * * @param buf Array of bytes to convert to hex string * @return Generated hex string */ View Complete Post(); Hi I have Java script , when i close my .aspx page getting yes/no message, i want do disable this message , dont want any message befroe close my window how i can do I Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend
http://www.dotnetspark.com/links/61481-aes---encrypt-message-java--decrypt-asp-net.aspx
CC-MAIN-2017-13
refinedweb
185
65.76
Reusable SVG component in React SVG is one of the image formats you want to use in JavaScript application. The question of why to choose SVG over other image formats is a separate topic to discuss. In this short tutorial, I would like to show how I handle SVG elements in React applications. React gives us few options to use SVG in components. You can paste the SVG content inline, in any of your components. This solution is not advised. Your component code will be bloated with the svg code, there's no reusability. The example below is just an example. The SVG code won't give any output if you try to open it. Usually, the SVG files are more complex. import React from 'react'; const User = () => { return ( <div className="user__avatar"> <svg xmlns="" viewBox="0 0 841.9 595.3"> <g fill="#61DAFB"> < </g> </svg> </div> ) }; The next option is to transform your svg file directly into a React component. This can be done using SVGR package. I won't explain how it works in detail but here's the snippet that shows how simple it is. After the configuration you just need to include your SVG as a component, the optimization will be handled by SVGR. import React from 'react'; import MyLogo from './myLogo.svg'; const User = () => { return ( <div className="user__avatar"> <MyLogo /> </div> ) }; If your React application is bootstrapped using the create-react-app SVGR webpack loader is already included in your configuration. This should be enough in most cases but I needed to create a generic and reusable container for SVG icons. I wanted to avoid styling vector elements in each component and store them in a separate component. To handle this I created this simple component. Note that I use styled-components and typescript. svgIcon.tsx import React from "react" import { SvgContainer } from "./svgicon-styles" interface Props { Icon: React.FunctionComponent<React.SVGProps<SVGSVGElement>> width?: number height?: number } const SvgIcon: React.FC<Props> = props => { const { Icon } = props return ( <SvgContainer {...props}> <Icon /> </SvgContainer> ) } export default SvgIcon And here is the styled component: svgicon-styles.ts import styled from "styled-components"; export const SvgContainer = styled.div<{ height?: number width?: number }>` height: "auto"; width: "auto"; display: inline-flex; align-items: center; justify-content: center; & svg { height: ${props => (props.height ? `${props.height}px` : "100%")}; width: ${props => (props.width ? `${props.width}px` : "100%")}; } ` The only thing to make this work is to pass the icon component into SvgIcon. Now all SVG's in my project are adjusted to the parent container. If I need to set other dimensions to the icon, I have to pass the appropriate width or height prop in the desired component. So far I've needed to change only the width and the height using props, but it's easily extendable. Other properties might be added to manipulate the SVG using props. User.tsx import React from 'react'; import SvgIcon from "../../shared/SvgIcon/svgIcon"; import { ReactComponent as MyIcon } from "../icons/myIcon.svg"; const User: React.FC = () => { return ( <div className="user__avatar"> <SvgIcon Icon={MyIcon} width={35} /> </div> ) }; Before I add any SVG into the project I optimize its code. For now, I can achieve it using this tool. Just paste the SVG code and choose any from the available features. You can minify the code, prettify markup, and optimize the whole SVG file. Conclusion Wrapping the SVG icon into a separate component is helpful when it comes to unifying the appearance of these elements across your application. Using this component along with the SVGR package or other SVG optimization tool will make your icons easily scalable and editable. This may also increase the performance and speed of your website.
https://michalmuszynski.com/blog/reusable-svg-component-in-react/
CC-MAIN-2022-33
refinedweb
610
58.48
One option is using an ide such as Jbuilder (can others do this?) is to make your application or libraray a jar and specify that any dependant classes are compiled into the jar as well. This allows you to bundle the required versions into the jar (assuming there are no namespace clashes which jakarta avoids nicely) along with all your code and run it that way. Not the nicest and not the easiest to maintain but if you really want it all in one jar that's one way. I use this to bundle libraries up when I'm providing users with a java app and I don't want to have to muck around with batch files and sorting out common directory structures on their PC's (since they end up messing these up) So I create a jar as above. Give it a manifest identifying the main class then concat the file with the following header (CRLF just means new line) java -jar nameOfMyJar.bat<CRLF> Then rename the resulting file to nameOfMyJar.bat. They double click on it the app runs. If you want to know if there was a problean put a pause in: java -jar nameOfMyJar.bat<CRLF> Pause<CRLF> Hacky but I've had no maintenance hassles over it since I gave it to them... Matt -----Original Message----- From: Timko, Cheryl A. [mailto:cheryl_timko@merck.com] Sent: 09 May 2003 13:22 To: 'commons-user@jakarta.apache.org' Subject: [Commons] Component Packaging Options All, I was hoping someone else had experienced this dilemma using the Jakarta Commons components... I have created a company-wide shared component which utilizes the Digester and DBCP component. Both the Digester and DBCP components are dependent on other Jakarta Common components. Since I tested and validated my shared component with the specific versions of the Jakarta Commons components, I want to package these Jakarta Common versions with my component (I do not want other versions to be used).())? Any suggestions would be greatly appreciated... > Cheryl Timko > USHH IS Application Architecture > * WP97-A315 > * 215-652-8822 > * cheryl_timko. ============================================================================ == --------------------------------------------------------------------- To unsubscribe, e-mail: commons-user-unsubscribe@jakarta.apache.org For additional commands, e-mail: commons-user.
http://mail-archives.apache.org/mod_mbox/commons-user/200305.mbox/%3C73E71EF16978D51197180002A56022D20743C545@ngmnt4mbx03.uk.capitalone.com%3E
CC-MAIN-2016-26
refinedweb
364
62.98
1if access is allowed, 0if not. See the Unix man page access(2) for more information. Availability: Unix, Windows.; Universal Naming Convention paths are those that use the ` \\host\path' syntax).defines functions and constants that are useful for extracting information from a stat structure. (On Windows, some items are filled with dummy values.) Availability: Macintosh, Unix, Windows. Changed in version 2.2: Added access to values as attributes of the returned object. For compatibility with older Python versions, accessing stat_result as a tuple always returns integers. For compatibility with Python 2.2, accessing the time stamps by field name also returns integers. Applications that want to determine the fractions of a second in a time stamp can use this function to have time stamps represented as floats. Whether they will actually observe non-zero fractions depends on the system. Future Python releases will change the default of this setting; applications that cannot deal with floating point time stamps can then use this function to turn the feature off.definesnames itself is generated. By default errors from the os.listdir() call are ignored. If optional argument onerror is specified, it should be a function; it will be called with one argument, an os.error: import os from os.path import join # Delete everything reachable from the directory named in 'top'. # CAUTION: This is dangerous! For example, if top == '/', it # could delete all your disk files. for root, dirs, files in os.walk(top, topdown=False): for name in files: os.remove(join(root, name)) for name in dirs: os.rmdir(join(root, name)) New in version 2.3. See About this document... for information on suggesting changes.See About this document... for information on suggesting changes.
http://docs.python.org/release/2.3.3/lib/os-file-dir.html
crawl-003
refinedweb
286
62.85
WebKit Bugzilla This is a subtask of Add two things to the webkit API. 1) WebURLRequest TargetTypes for worker and shared worker main resources. 2) Factory method on class WebCommonWorkerClient to createApplicationCacheHost() for the associated worker. Created attachment 54348 [details] patch Comment on attachment 54348 [details] patch Rejecting patch 54348 from commit-queue. michaeln@google@chromium.org to request a commit-queue restart. After restart the commit-queue will correctly respect your committer rights. Attachment 54348 [details] did not build on chromium: Build output: (In reply to comment #3) > Attachment 54348 [details] did not build on chromium: > Build output: I missed a derived class in DRT/chromium! New patch coming soon (this time with commit-queue?) Created attachment 54358 [details] added DRT/chromium mods Created attachment 54362 [details] add some WebKit:: namespace prefixes Target types are defined bun not used in this patch. Can they be a part of some other patch, where they are actually used? Or are they sued entirely in the code that is not part of the WebKit repo? I'm just touching the webkit API in this patch. I have a subsquent webcore patch that defines corresponding enum values in webcore and uses them. See Comment on attachment 54362 [details] add some WebKit:: namespace prefixes And a small nit: > Index: WebKit/chromium/src/WebWorkerBase.cpp > +void WebWorkerBase::didCreateDataSource(WebFrame* frame, WebDataSource* ds) > +{ > + // Tell the loader to load the data into the 'shadow page' synchronously, > + // so we can grab the resulting Document right after load. > + static_cast<WebDataSourceImpl*>(ds)->setDeferMainResourceDataLoad(false); > +} 'frame' is not used in this function, should be omitted. Almost there. ? (In reply to comment #10) > ? We could smush them together. I had them broken up for a few reasons. 1) I thought we liked smaller patches. If i put them together i could just as easily hear "maybe you should separate the API from the webcore changes" which sounds just as valid as "please smush them together". 2) Chrome has compile time dependencies on the API. Once landed, its in and I can code to it in chrome. If smushed together, there's a chance that this will hiccup somewhere and get rolled out. If the API changes are rolled out after chrome depends on it, that could break the Chrome build. 3) Need to run the webcore changes thru webkit tests and that's easier said than done on windows. I went with two patches for those reasons. The one that bugs me the most is the second item. Created attachment 54494 [details] take4 Removed the unused param name per dimich's comment. Also added a call to frame->setClient(NULL) in the dtor since we're no longer using a global frameClient instance. Attachment 54494 [details] did not pass style-queue: Failed to run "['WebKitTools/Scripts/check-webkit-style', '--no-squash']" exit_code: 1 WebKit/chromium/src/WebWorkerBase.cpp:84: Use 0 instead of NULL. [readability/null] [5] Total errors found: 1 in 8 files If any of these errors are false positives, please file a bug against check-webkit-style. Given that frames are refcounted objects with 'squishy' lifetimes. I'd be more comfortable with an explicit call to setClient(NULL) at WebWorkerBase dtor time. I just stepped thru in the debugger to see the sequence of events. Under normal circumstances this definitely isn't needed... but since 'frames' are refcounted there may be cases where it actually outlives WebWorkerBase. I'll post the webcore changes in a second patch for review coincident with this one. I'd like to keep them in different patches for the reasons mentioned earlier. Created attachment 54509 [details] replace NULL with 0 Comment on attachment 54509 [details] replace NULL with 0 r=me Comment on attachment 54509 [details] replace NULL with 0 Clearing flags on attachment: 54509 Committed r58380: <> All reviewed patches have been landed. Closing bug.
https://bugs.webkit.org/show_bug.cgi?format=multiple&id=38147
CC-MAIN-2015-14
refinedweb
641
65.22
About Topics and Namespaces Hi all, I'm new in ROS (I'm using Indigo and Ubuntu 16.04), so in order to start to manage ROS environments I have launched the dataset prepared for an algorithm that I have studied (concretely, SVO). But at this point, some doubts arise. First of all, can one topic have differents kinds of messages? I explain it: I executed commands "rostopic echo /svo/keyframes" and "rostopic echo /svo/points" to see what is published in these topics. According to ROSwiki, tutorials I had seen, and my rqt_graph, I thougth that "svo" is the namespace; but in rviz appears the following fields (Namespaces looks like belong to topics...) Does it mean that in the same topic ("/svo/points") are being published points from map and from trajectory? Then, how could I see this in rostopic? Default info displayed is only about trajectory points Same doubt for the the topic /svo/keyframes with cams and kfs namespaces Thank you so much in advance! Hope anyone can clarify my confusion :) Edit: Thank you very much for response! It's clearer now. There you'd need to more details about the node you are using. I tried to link a screenshot that showed my rviz settings, but I don't know why I did it wrong... so I am going to describe it with more details: "svo" is a node which publishes in the topics "/svo/points" and "/svo/keyframes". I have 2 Markers to visualize these 2 topics in rviz, one for "/svo/points" and the other for "/svo/keyframes". Both of them, in their rviz Marker, have a dropdown field called 'Namespaces', with 2 options each. For example, in "/svo/points" appear namespace 'pts' (for points on the map) and namespace 'trajectory' (por points that recover the camera path). According to your reply, both ('pts' and 'trajectory') are published with same message format in "/svo/points" topic. Okey, I understand it. But when I execute rostopic echo command with this topic, the bash only displays info about points regardindg to 'trajectory' namespace. So, my doubts are - Are 'pts' and 'trayectory' a namespaces within "/svo/points" topic? - How could I see info for 'pts' points with rostopic echo? (By default only displays info for 'trajectory' namespace) I hope I have expressed myself better. Thanks again. BR. Do not post updates as answers, unless you are answering your own question. To add more information or to clarify something, edit your original question (using the editbutton/link) or post a comment. Edit: I've also just given you sufficient karma to post your RViz screenshot. So please do so. Sorry, I'll keep it in mind next time. Thanks.
https://answers.ros.org/question/330926/about-topics-and-namespaces/
CC-MAIN-2021-04
refinedweb
451
72.76
Hi, i'm trying to learn more about how Lexical Analyzers/Parsers work. I haven't coded any classes yet, because i'm not really sure how the entire process from a Lexer to working code goes. My goal is to write a simple made up programming language and translate that to another language, like Javascript. The first thing i have to do is give the code to a Lexical Analyzer. The lexer will split the source into tokens and assign a label to it. So suppose i have the following code: Code: def myVar = 10; The lexer will split that into token like this: Code: def -> keyword myVar -> Identifier = -> Operator 10 -> Number That's basically as far as i understand what a lexer does. How can i translate the tokens to a language like Javascript?? From what i understand i need to write a Parser class. But i couldn't find any info on what that class exactly does. So what is exactly the next step i have to take? def myVar = 10; def -> keyword myVar -> Identifier = -> Operator 10 -> Number Originally Posted by vivendi So what is exactly the next step i have to take? The next step is too much to explain on a programming board. Better you get a book on compiler theory (The Dragon Book is one), as that describes in detail the lexical analysis, parser, syntactic analysis, and then finally code generation (the JavaScript generation). You need all of these to accomplish what you're doing. More than likely, you would have built some sort of syntax tree after the lexical analysis, parsing, and then syntax analysis have been done. Then you have to write something ( a translator) that can read the syntax tree and convert what the syntax tree describes into JavaScript. Regards, Paul McKenzie Last edited by Paul McKenzie; October 6th, 2012 at 12:13 PM. Be prepared to do a LOT of research and programming. compiler technology is quite a broad subject and it's a highly technical bit of knowledge. It is not something you'd want to start with unless you are very familiar with programming as is. As for the translator... This seems somewhat of a strange thing to do. A lot of effort to automate a process that is hard to automate to begin with. Especially if your target is javascript which is different from a technological approach to a language like C/C++. If you want to learn about lexers and parsers in general then there are easier tasks than a programming language translator. Especially considering even "small" computer languages tend to have considerable grammars. Forum Rules
http://forums.codeguru.com/showthread.php?528229-Writing-a-Lexical-Analyzer-Parser&p=2087785
CC-MAIN-2017-09
refinedweb
440
63.19
There are situations where multiple inheritance is the best (if not the only) choice when designing a certain model for our program or project. C# unfortunately does not support multiple inheritance and so we must look for ways to adapt our design to make possible its implementation. But C# does offer resources and tricks that can be used to simulate multiple inheritance without radically redesigning our class model, with only adding several auxiliary methods and classes and taking one or two precautions while coding them. I propose a design pattern that lets us simulate multiple inheritance in a C# program in a way that produces classes that behave almost like they were really extended from two or more parent classes. We will face classical multiple inheritance problems too and will see how to address them. Most recent languages like C#, Java, Delphi, have simple inheritance. They don't have multiple inheritance because their designers had to choose between have it in and have all the problems it comes with, or get it out of the language putting away all those problems, and introduce a versatile and less problematic substitute like interfaces and interface inheritance. Multiple inheritance has multiple problems that we will discuss later. But those problems are quite pathological and do not arise in any program in which multiple inheritance could be useful or could be the most appropriate design. There are traditional ways to emulate multiple inheritance with interface inheritance with more or less success. Let's suppose we have two classes, A and B, and we want C to inherit from both of them. class A { m1(); } class B { m2(); } class C : A, B { m1(); m2(); } That code is impossible in C#. The following is the classical workaround to deal with this: class A { m1(); } interface IB { m2(); } class B : IB { m2(); } class C : A, IB { B BObject; m1(); m2() { BObject.m2(); } } In this code, we make class B to implement a new interface named IB that has identical methods as those of B. Then class C inherits from A and IB, and uses an internal B object that replicates B's m2 method implementation. So C.m2 in fact calls its BObject.m2 method. Then we can say C now has A's implementation of m1() and B's implementation of m2(). And we can use C object wherever we could use A objects or IB objects. But this solution has several problems. One of them is the fact that we can't use C objects where explicitly B objects are expected, but only where IB objects are. So maybe we will have to change all the other code in the project, replacing references to B objects with references to IB objects. That will not be a big problem if we are designing the model and can take such decisions. But if the project is dependant on third party code or the standard library (the Framework) then we will be unable to make those modifications. Even more important, if class B is not ours, but it is from the standard library or from third party code, we can't make it implement our IB interface. We can't touch it. We have seen that we cannot simulate multiple inheritance completely using only interfaces and simple inheritance. We need something more, and C# happens to have that. Let's see. We have these objectives: Cto inherit from classes Aand B, being able to call their implementation of their methods with no need to rewrite them. Cobjects wherever an Aobject or Bobject is expected. Aor B, for they are untouchable for one or another reason, or we simply don't care. Cobjects just like normal objects. publicfields, but use properties instead. However, this pattern will work even if one of the parent classes (at most) exposes publicfields. Here is the basic idea: We will create two auxiliary classes, Aaux and Baux that inherit from A and B respectively. class A { m1(); } class B { m2(); } class Aaux : A { m1(); } class Baux : B { m2(); } Our new class C won't inherit from A or B but have the same methods of both of them. Besides, it will contain two objects: one of type Aaux and the other of type Baux. We will call them C.APart and C.BPart respectively. C will use their implementations of m1 and m2 instead of rewriting them. class C { Aaux APart; Baux BPart; m1() { APart.m1(); } m2() { BPart.m2(); } } So every C object has a pair of A and B objects inside. Let's make those objects know who is containing them by adding a reference to the C object that contains them. We will modify classes Aaux and Baux for this purpose: class Aaux : A { C CPart; m1(); } class Baux : B { C CPart; m2(); } And finally we arrive at the final trick. We will redefine the implicit casting operator for class C, so: Aobject is expected and a Cobject is found, C.APartis returned. Bobject is expected and a Cobject is found, C.BPartis returned. Again, we will redefine the implicit casting operator for class Aaux so whenever a C object is expected and an Aaux object is found, Aaux.CPart is returned. Identically, we will redefine the implicit casting operator for class Baux so whenever a C object is expected and a Baux object is found, Baux.CPart is returned. This is the final look: class Aaux : A { C CPart; m1(); static implicit operator C(Aaux a) { return a.CPart; } } class Baux : B { C CPart; m2(); static implicit operator C(Baux b) { return b.CPart; } } class C { Aaux APart; Baux BPart; m1() { APart.m1(); } m2() { BPart.m2(); } static implicit operator A(C c) { return c.APart; } static implicit operator B(C c) { return c.BPart; } } Now given that code, we can use C objects wherever an A or B object is expected, in addition to where a C object is expected. The only cost has been adding two extra classes and requiring the parent classes not to expose public fields. However, there is another step we can take that will allow us to reduce in on the number of extra classes required and will let one of the parent classes have public fields. In fact, the class diagram will be even simpler. We only have to make C inherit directly from A, the class which exposes public fields. Of course, properties are fully compatible with this pattern, since they behave like methods. So parent classes may have as many public properties as they wish. Let's see an example. We are a computer dealer that buys computer hardware from major vendors and sells it to end users. However, we often get out of stock and we avoid losing customers by buying from rival computer shops and re-selling to our customers. We are not the only ones with that policy, so other shops often purchase our goods for selling them later. Our program has two arrays - in one of them we keep all our vendors, and in the other we keep all our customers. Rival shops are both vendors and customers. This would be the idea: class Vendor {...} class Customer {...} class Shop : Vendor, Customer {...} And this could be the final code (it's available in the download): /// <summary> /// A computer manufacturer. They resupply us. /// </summary> public class Vendor { string id; public string VendorId { get { return id; } set { id = value; } } public Vendor(string vendorId) { id = vendorId; } public virtual void AskForRessuply() { Console.WriteLine("Please ressuply me, vendor "+id+"."); } } /// <summary> /// A customer. We send them their purchased goods. /// </summary> public class Customer { string name; public string Name { get { return name; } set { name = value; } } public Customer(string customerName) { name = customerName; } public virtual void SendOrder() { Console.WriteLine("Dear "+name+": We are sending your goods."); } } /// <summary> /// The auxiliary class that redefines Customer. /// </summary> internal class CustomerAux : Customer { // <--- It has a link to the Shop object that contains it. internal Shop shopPart; internal CustomerAux(string customerName) : base (customerName) { } // We declare the implicit casting operator for returning // shopPart when a Shop object is expected. static public implicit operator Shop(CustomerAux c) { return c.shopPart; } } /// <summary> /// We consider a shop like a Vendor and a Customer, /// for we both ask them to resupply us, /// or they purchase our goods. /// </summary> public class Shop : Vendor // <-- It inheirs only from Vendor... { CustomerAux customerPart; // ...but has a CustomerAux object inside. // Shops have an address in addition to the vendor id // and the customer name inherited from Vendor and Customer. string address; public string Address { get { return address; } set { address = value; } } // Here we are 'redirecting' property Name to the customerPart object. public string Name { get { return customerPart.Name; } set { customerPart.Name = value; } } // The Shop constructor. public Shop(string vendorId, string customerName, string shopAddress) : base (vendorId) { // We create and bind the CustomerAux object to this one. customerPart = new CustomerAux(customerName); customerPart.shopPart = this; address = shopAddress; } // Here we are redirecting Customer.SendOrder to the customerPart object. public virtual void SendOrder() { customerPart.SendOrder(); } // We redefine the implicit casting operator for returning // customerPart when a Customer object is expected. static public implicit operator Customer(Shop s) { return s.customerPart; } } // An example of use of the Vendor, Customer and Shop classes. class EntryPoint { static void Main(string[] args) { Vendor ibm = new Vendor("32FK-IBM"); Vendor hp = new Vendor("1138-HP"); Customer mrSimpson = new Customer("Mr. Simpson"); Customer mrGates = new Customer("Mr. Gates"); Shop joys = new Shop("1979-JCS", "Joy's Computer Shop", "123, Fake St."); Vendor[] vendors = {ibm, hp, joys}; foreach(Vendor ven in vendors) ven.AskForRessuply(); Customer[] customers = {mrSimpson, mrGates, joys}; foreach(Customer cus in customers) cus.SendOrder(); Console.ReadLine(); } } One of the most important problems of multiple inheritance is caused by this situation: Class A has the m1() method. The [ImpA] means that method m1 has been implemented in A. Classes B and C inherit from A, and both of them redefine method m1. So class B has its own implementation of m1, denoted by [ImpB], and class C has its own implementation of m1 too, denoted by [ImpC]. Now class D inherits from B and C. The problem is... what implementation of m1 is used while running this code? D d = new D(); d.m1(); ...this code? B d = new D(); d.m1(); ...and this code? C d = new D(); d.m1(); Languages and compilers supporting multiple inheritance solve this in one way or the other. But this makes compiling, debugging and understanding the code more difficult. Often the version of the implementation of m1 to be run is nearly unpredictable. However, this pattern solves to certain degree that problem, because we can choose what implementation will be run. Assuming our D class uses our pattern for simulating multiple inheritance, there will be five different situations: Dredefines m1and we always want its implementation to be used: We just have to make D.BPart.m1()and D.CPart.m1()to call D.m1(). B's implementation: Then we make D.m1()and D.CPart.m1()call D.BPart.m1(). C's implementation: Then we make D.m1()and D.BPart.m1()call D.CPart.m1(). B's implementation when m1is called from a Btype variable, C's implementation when m1is called from a Ctype variable, and D's new implementation when called from a Dtype variable: Just redefine m1in Dclass and let D.BPartand D.CPartalone. (This option is not recommendable except when we know what we are doing.) Dobject at call time: We write different implementations of m1in D.m1(), D.BPart.m1(), and D.CPart.m1(). (This is even less recommendable than the previous one. But it could be useful for someone.) Multiple inheritance was not included in C# for important reasons. However, I sometimes miss it and that is the reason why I proposed this pattern. I think it may be useful for those who find more advantages in its application than disadvantages. I'd like to see your comments on it, telling problems I didn't see and advices for enhancement. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/architecture/smip.aspx
crawl-002
refinedweb
2,004
57.06
A module for lazy loading of Python modules Project description lazy_import provides a set of functions that load modules, and related attributes, in a lazy fashion. This allows deferring of ImportErrors to actual module use-time. Likewise, actual module initialization only takes place at use-time. This is useful when using optional dependencies with heavy loading times and/or footprints, since that cost is only paid if the module is actually used. For minimal impact to other code running in the same session lazy_import functionality is implemented without the use of import hooks. lazy_import is compatible with Python ≥ 2.7 or ≥ 3.4. Examples: lazy module loading import lazy_import np = lazy_import.lazy_module("numpy") # np is now available in the namespace and is listed in sys.modules under # the 'numpy' key: import sys sys.modules['numpy'] # The module is present as "Lazily-loaded module numpy" # Subsequent imports of the same module return the lazy version present # in sys.modules import numpy # At this point numpy and np point to the same lazy module. # This is true for any import of 'numpy', even if from other modules! # Accessing attributes causes the full loading of the module ... np.pi # ... and the module is changed in place. np and numpy are now # "<module 'numpy' from '/usr/local/lib/python/site-packages/numpy/__init__.py'>" # Lazy-importing a module that's already fully loaded returns the full # module instead (even if it was loaded elsewhere in the current session) # because there's no point in being lazy in this case: os = lazy_import.lazy_module("os") # "<module 'os' from '/usr/lib/python/os.py'>" In the above code it can be seen that issuing lazy_import.lazy_module("numpy") registers the lazy module in the session-wide sys.modules registry. This means that any subsequent import of numpy in the same session, while the module is still not fully loaded, will get served a lazy version of the numpy module. This will happen also outside the code that calls lazy_module: import lazy_import np = lazy_import.lazy_module("numpy") import module_that_uses_numpy # This module will get a lazy module upon # 'import numpy' Normally this is ok because the lazy module will behave pretty much as the real thing once fully-loaded. Still, it might be a good practice to document that you’re lazily importing modules so-and-so, so that users are warned. Further uses are to delay ImportErrors: import lazy_import # The following succeeds even when asking for a module that's not available missing = lazy_import.lazy_module("missing_module") missing.some_attr # This causes the full loading of the module, which now fails. "ImportError: __main__ attempted to use a functionality that requires module missing_module, but it couldn't be loaded. Please install missing_module and retry." Submodules work too: import lazy_import mod = lazy_import.lazy_module("some.sub.module") # mod now points to the some.sub.module lazy module # equivalent to "from some.sub import module as mod" # Alternatively the returned reference can be made to point to the # base module: some = lazy_import.lazy_module("some.sub.module", level="base") # This is equivalent to "import some.sub.module" in that only the base # module's name is added to the namespace. All submodules must be accessed # via that: some.sub # Returns lazy module 'some.sub' without triggering full loading. some.sub.attr # Triggers full loading of 'some' and 'some.sub'. some.sub.module.function() # Triggers loading also of 'some.sub.module'. Finally, if you want to mark some modules and submodules your package imports as always being lazy, it is as simple as lazily importing them at the root __init__.py level. Other files can then import all modules normally, and those that have already been loaded as lazy in __init__.py will remain so: # in __init__.py: import lazy_import lazy_import.lazy_module("numpy") lazy_import.lazy_module("scipy.stats") # then, in any other file in the package just use the imports normally: import requests # This one is not lazy. import numpy # This one is lazy, as long as no other code caused its # loading in the meantime. import scipy # This one is also lazy. It was lazily loaded as part of the # lazy loading of scipy.stats. import scipy.stats # Also lazy. import scipy.linalg # Uh-oh, we didn't lazily import the 'linalg' submodule # earlier, and importing it like this here will cause # both scipy and scipy.linalg (but not scipy.stats) to # immediately become fully loaded. Examples: lazy callable loading To emulate the from some.module import function syntax lazy_module provides lazy_callable. It returns a wrapper function. Only upon being called will it trigger the loading of the target module and the calling of the target callable (function, class, etc.). import lazy_import fn = lazy_import.lazy_callable("numpy.arange") # 'numpy' is now in sys.modules and is 'Lazily-loaded module numpy' fn(10) # array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) lazy_callable is only useful when the target callable is going to be called: import lazy_import cl = lazy_import.lazy_callable("numpy.ndarray") # a class obj = cl([1, 2]) # This works OK (and also triggers the loading of numpy) class MySubclass(cl): # This fails because cl is just a wrapper, pass # not an actual class. Installation pip install lazy_import Or, to include dependencies needed to run regression tests: pip install lazy_import[test] Tests The lazy_module module comes with a series of tests. If you install with test dependencies (see above), just run import lazy_import.test_lazy lazy_import.test_lazy.run() # This will automatically parallelize over the available number of cores Alternatively, tests can be run from the command line: pytest -n 4 --boxed -v --pyargs lazy_import # (replace '4' with the number of cores in your machine, or set to 1 if # you'd rather test in serial) Tests depend only on pytest and pytest-xdist, so if you didn’t install them along lazy_import (as described under Installation) just run pip install pytest pytest-xdist Note that pytest-xdist is required even for serial testing because of its --boxed functionality. License lazy_import is released under GPL v3. It was based on code from the importing module from the PEAK package. The licenses for both lazy_import and the PEAK package are included in the LICENSE file. The respective license notices are reproduced here: lazy_import — a module to allow lazy importing of python modules lazy_import is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. lazy lazy_import. If not, see <>. The PEAK importing code is”. :) Code pertaining to lazy loading from PEAK importing was included in lazy_import, modified in a number of ways. These are detailed in the CHANGELOG file of lazy_import. Changes mainly involved Python 3 compatibility, extension to allow customizable behavior, and added functionality (lazy importing of callable objects). Project details Release history Release notifications Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/lazy-import/
CC-MAIN-2019-51
refinedweb
1,165
56.76
C# & ASP.NET Developer BLOG I have just recently designed a site for a client and decided to use MVC for it. I think above all the best thing I enjoy about it, is the clean markup that is outputted. Of course I also have great administration for the work and effort that has gone into the actual framework, it is superb! So what I wanted to share with this post is simply how easy it is to create a contact form for your website. We will include 4 fields, being Full name, Telephone, Email Address and Enquiry. So to encapsulate everything we need here I will bullet these out: This is the action which we will use as the action attribute for our form. You will see I create an instance of our enquiry model, and after sending the email I forward this model onto the thank you view. You need to include the using statement for System.Net.Mail public ActionResult SendContactForm(string Name, string Telephone, string Email, string Enquiry) { Models.Enquiry enq = new MvcApplication.Models.Enquiry(Name, Telephone, Email, Enquiry); MailAddress addressTo = new MailAddress("email@awebsite.co.uk"); MailAddress addressFrom = new MailAddress("noreply@anotherwebsite.co.uk"); MailMessage message = new MailMessage(addressFrom, addressTo); message.Subject = "Website Enquiry"; System.Text.StringBuilder sb1 = new System.Text.StringBuilder(); sb1.AppendLine(String.Format("<p><span style='float:left;width:200px;font-weight:bold;display:block;'>Name</span> : {0}</p>", Name)); sb1.AppendLine(String.Format("<p><span style='float:left;width:200px;font-weight:bold;display:block;'>Telephone Number</span> : {0}</p>", Telephone)); sb1.AppendLine(String.Format("<p><span style='float:left;width:200px;font-weight:bold;display:block;'>Email</span> : {0}</p>", Email)); sb1.AppendLine(String.Format("<p><span style='float:left;width:200px;font-weight:bold;display:block;'>Enquiry</span> : {0}</p>", Enquiry)); message.IsBodyHtml = true; message.Body = sb1.ToString(); SmtpClient s = new SmtpClient("127.0.0.1", 25); s.Send(message); return View("Thankyou", enq); } In the above code sample you can see the class, Models.Enquiry. That is our model and the simple code for it is below. Nothing special but does the job. namespace MvcApplication.Models { public class Enquiry { private string m_name; public string Name { get { return m_name; } set { m_name = value; } } private string m_telephoneNumber; public string TelephoneNumber { get { return m_telephoneNumber; } set { m_telephoneNumber = value; } } private string m_email; public string Email { get { return m_email; } set { m_email = value; } } private string m_enquiry; public string Enquiry1 { get { return m_enquiry; } set { m_enquiry = value; } } public Enquiry(string name, string telephoneNumber, string email, string enquiry) { m_name = name; m_telephoneNumber = telephoneNumber; m_email = email; m_enquiry = enquiry; } } } This was due to me experiencing the rendering of the input tag with upper case "C" of the class attribute. If you try and construct the input Html Helper with new {class="YourClass"} the compiler thinks you are actually creating a class object and not a variable. So you have to use new {Class="YourClass"} . This works, and it renders correctly in HTML, but as I said above, this is not valid for XHTML Strict. So I simply made use of the .NET 3.5 framework and created an extension method for this. public static string TextBoxWithClass(this System.Web.Mvc.HtmlHelper helper,string name, string CssClass) { string"; format = String.Format(format,name, CssClass); return format; } I will then use the above inside the form which I will show next. So you will see below, I want to assign the class name of WithBorder to each TextBox. One thing which I will mention, is that inside the Markup for the view I have included the following line so that my extension methods are seen. Notice the action attribute in the form. As usual you can use either POST or GET as the method for your form. I prefer POST simply because I don't want the contents of the Request.Form key value pairs inside the URL. <%@ Import Namespace="MvcApplication.Classes" %> <div id="GeneralEnquiry" class="enquiryForm"> <form action="/Home/SendContactForm" method="post"> <p> <span>Name</span> <%= Html.TextBoxWithClass("Name","WithBorder") %> </p> <p> <span>Telephone Number</span> <%= Html.TextBoxWithClass("Telephone", "WithBorder")%> </p> <p> <span>Email Address</span> <%= Html.TextBoxWithClass("Email", "WithBorder")%> </p> <p> Enquiry</p> <p> <%= Html.TextAreaWithClass("Enquiry","WithBorder")%> </p> <p> <%=Html.SubmitButton("btnSubmit", "Send Enquiry")%> </p> </form> </div> Finally you need a view for your thank you page which you render inside the action for the contact script. I have not used the Model which I forward to the page, but in essence a scenario would be you could confirm with the client the actual details of what they sent you in the form. <h2> Thank you for your enquiry</h2> <p> Your enquiry has been sent, we will reply to your enquiry as soon as possible. Thank you.</p> If I used the Model I could access like this: <ul> <li>Name : <%= ViewData.Model.Name %></li> <li>Telephone Number : <%= ViewData.Model.TelephoneNumber %></li> <li>Email : <%= ViewData.Model.Email %></li> </ul> Cheers for now, Andrew :-) Pingback from A Simple MVC Preview 3 Contact Form, Custom HtmlHelper and Model Example - Andrew Rea I believe {_class="YourClass"} works and produces valid XHTML. Anyway, nice sample. Would you Enquiry class be a good candidate for automatic properties and also leverage Object Initializers to eliminate that greedy constructor? Debug Setting .NET breakpoints in Windbg for applications that crash on startup Web Javascript HTML Construction FYI: You can use a reserved keyword in C# (such as class) by prepending @. So, you can get the input tag you want using the built-in helper if you pass into Html.TextBox's htmlAttributes parameter: new { @class = "YourClass" } The compiler no longer thinks you're trying to create a new class and the resulting XHTML attribute is properly cased. Link Listing - June 5, 2008 itsmecurtis : Great Tip, much apreciated! I use that notation say when I want to create an unescaped string, but never knew I could use it in such context. Again, thanks for your input! :-) Top Tip. Eric : I will definately look into them, thanks for the comment How to create DropDownList onchange event in MVC Pingback from ASP.NET MVC Archived Buzz, Page 1
http://weblogs.asp.net/andrewrea/archive/2008/06/05/a-simple-mvc-preview-3-contact-form-custom-htmlhelper-and-model-example.aspx
crawl-002
refinedweb
1,017
57.47
18 May 2012 06:38 [Source: ICIS news] KUALA LUMPUR (ICIS)--China’s Hengli Petrochemical will have to push back the start-up of its 2.2m tonne/year No 1 purified terephthalic acid (PTA) unit in Dalian to September-October as construction of a ship berthing port at the project site has been delayed, a source said with the matter said on Friday. The Chinese polyester major had initially targeted to start-up the PTA unit in end-July. The company’s PTA site in ?xml:namespace> “Both the No 1 and No 2 units will be mechanically complete by July, but they are not able to receive sufficient amounts of feedstock paraxylene to begin trial runs,” the source said. The company has 16 chemical tanks at Dalian that are capable of storing up to 600,000 tonnes of feedstock PX. Hengli Petrochemical's No 2 PTA unit at the site also has a 2.2m tonne/year capacity. Hengli Petrochemicals is targeting to start up the No 2 PTA unit two months after the No 1 unit achieves commercial
http://www.icis.com/Articles/2012/05/18/9560941/apic-12-chinas-hengli-petchem-delays-dalian-pta-unit-start-up.html
CC-MAIN-2013-48
refinedweb
181
69.72
I'm really confused right now about this compiling issue with my code for the C++ style strings tutorial (took a break from programming and came back, so I haven't advanced much). Code:#include <iostream> #include <string> using namespace std; int main() { string review; string::size_type length; length = review.length(); int bad; int timesofword; for (bad = review.rfind("bad", review.end()); bad != string::npos; bad = review.rfind("bad", bad)) { timesofword++; bad++; cout<<timesofword<<endl; cin.get(); } } Results: 13 C:\Documents and Settings\Main\My Documents\stringnpos and find.cpp no matching function for call to `std::basic_string<char, std::char_traits<char>, std::allocator<char> >::rfind(const char[4], __gnu_cxx::__normal_iterator<char*, std::basic_string<char, std::char_traits<char>, std::allocator<char> > >)' I don't know at all how to fix it, and I've looked up a bunch of stuff on size_type (I think that's the problem), but still just cannot seem to figure this one out. Could anyone here please help me out and explain to me what I've done incorrectly?
http://cboard.cprogramming.com/cplusplus-programming/90941-rfind.html
CC-MAIN-2014-10
refinedweb
174
54.32
In my previous post on Re-factoring, Re-Structuring and the cost of Levelizing, I explained that increasing the value of the structure of a code base is less costly than expected. The point is to focus a while on Re-Structuring without changing any behavior (Re-Factoring). The biggest motivation for re-structuring code is to get rid of dependency cycles between your components (namespaces or assemblies). Once a code base is levelized (the proper term to say, once there are no more dependency cycles between your components), every refactoring task is naturally easier because you can always define clearly which levels of the code base are impacted. Personally I am a fan of evolutionary design as explained by Martin Fowler: With evolutionary design, you expect the design to evolve slowly over the course of the programming exercise. There’s no design at the beginning. You begin by coding a small amount of functionality, adding more functionality, and letting the design shift and shape. One point is that it is not possible to apply evolutionary design without a solid suit of automatic test. The risk of introducing regressions bugs would be too high. This is why I understand automatic tests as a way to mirror and scaffold the behavior of a code base. Once the code base and its automatic tests are in-sync (i.e when all tests are green), they both define the same behavior. If the behavior of the code gets modified, some tests are not in-sync anymore with the code. If the behavior delta is a regression bug, the code needs to be aligned with tests. If the behavior delta is a new feature/requirement, the tests need to be aligned with the code. The principle I would like to expose here is: Applying Evolutionary Design is easier once the components dependency graph has no cycles. Levelized components are of course not a replacement for a solid test suit, it doesn’t deal with correctness and behavior. But the point of this blog post is to show that levelized components it is a good complement to unit test to apply evolutionary design. The Need to define new Abstractions In the evolutionary design discipline, amongst all refactoring motivations, I estimate that the need to define new suited abstractions is essential. Concretely, in evolutionary design you are not supposed to create an interface implemented by one only class. The class is used by the consumer code, and if in the future you’ll get the need to provide a second or more implementations, then it will be time to create the interface, its associated factory, and the logic to plug with the correct implementation. Typically fool me once, don’t fool me twice. In other words: I was not supposed to anticipate the need for an abstraction the first time, but I won’t hesitate to create it when I will face the need a second time. Creating new Abstractions: the easy scenario Creating one abstraction to abide by one simple new requirement is easy. It becomes problematic when a massive new functional requirement will have impacts a bit everywhere in your code base. You’ll need to create many interfaces to create what is named an abstract façade. The typical case study is the need for some new RDMS. So far the application consumed only SQL Server data, but now it has also the need to consume Oracle data. This scenario is so typical that ADO.NET supports it out of the box. All the implementations to access a particular RDMS (what is named a data provider) can be encapsulated behind an abstract façade obtained from the System.data.Common.DBProviderFactory class. This data provider case study is seamless because the implementation of a data provider is cohesive and well decoupled from the rest of the .NET framework. Creating new Abstractions: the real-world complex scenario Let’s focus on a real-world example we had to face recently during the development of NDepend: the need was to let NDepend work on other platform than .NET, concretely Java first (the XDepend product) and then some others (C++ is in the pipe). The bulk of the code is platform agnostic and then, the idea makes sense in terms of Return over Investment. More precisely, the code specific to the .NET platform represents in terms of Lines of Code 11.8% of the whole code base and we can visualize it through the metric view: But this view represents what we obtained once we regrouped in a dedicated assembly the code specific to .NET. This code is isolated from the rest of the code base behind an abstract façade. At the beginning, the code specific to .NET was spawned all over the code base. This included the code needed to analyze .NET assemblies, the CQL specific .NET terminology (SELECT ASSEMBLIES…), the panel to let users define assemblies to analyze, the specific parsing of .NET coverage files, the Reflector and VisualStudio add-in, not to mention all the visual tool-tips and UI labels containing .NET specific vocabulary (IL code, assembly, attribute…). Concretely, in the metric view below, each blue rectangle represents a method/type/namespace/assembly that had some code specific to the .NET platform: We were in the typical evolutionary design problematic: since the beginning we didn’t bother with the fact that NDepend might be used on another platform than .NET. Basically the new design we decided to put in place looked like this: The fact that the code base was kept levelized since the beginning was a blessing to perform this massive re-structuring. That is what I am about to explain in 3 points. First, considering the sub-components (i.e the namespaces) of the new .NET specific assemblies, they were naturally levelized. At this point there were no questions like who’s high level, who’s low level, who’s depend on what. All these questions were already implicitly answered in the original design because it didn’t contain dependencies cycles. There were no questions also about which partitioning code in components, they already existed in the original design. Second, because the original design was levelized, the composition of interfaces in the abstract facade came naturally as a hierarchy. Here also the answer to questions like which interface present which feature and which property, were already contained in the original design. Third, the abstract façade needed to remain at the bottom level. Every component use it but it cannot use anything else than tier code (like primitive types). Actually we had a problem here. We defined a library to represent some strong-typed file and directory paths: NDepend.Helpers.FileDirectoryPath. We wanted the abstract façade able to expose such typed path objects. So the path library needed to be below the abstract facade. Fortunately, the path library didn’t use anything else than primitive types like string and char. This was not by chance but because the original code base was levelized. As roughly every components are using this path library, the path library has never been allowed to use anything else than tier code. Thus, placing the path library below the abstract façade was a matter of minutes. Dear reader, I am sure that you experienced in the past the joy of beging stuck many days to accomplish basically the same task on a real-world spaghetti/monster code base : rationalize dependencies to change the location of a component(s) in the overall structure of a code base (your best stories are welcomed in this post’s comments). Conclusion The lesson here is that keeping a code base levelized is an easy way to implicitly anticipate future requirements. Low-level components never get a chance to bubble-up in the architecture not because someone decided so, but because above components won’t let it bubble-up. Like in traditional building architecture, the structure itself put the pressure on low level components. In our example, the path library has never been allowed to use anything else than primitive types, not because we created a rule for that, but because it is roughly used everywhere in the code and we forbid dependencies cycles. A nice consequence is that keeping a code base levelized discards the need for most design decisions. Good design is implicitly and continuously maintained. There are no questions about what to do to implement new requirement. When planning new code to implement the un-forecasted requirement, you just have to consider its fan-in/fan-out (who will use this new code and who this new code will use). From this information and from the need to preserve levelization, you’ll infer the level and the right location where this new code needs to be added. Maybe you’ll need to use the injection of code or inversion of dependency patterns but only to preserve levelization, not because it seems cool to do so. And releases after releases, iterations after iterations, the design will evolve seamlessly toward something continuously flawless and unpredictable. Like in traditional building architecture, the structure won’t collapse.
http://codebetter.com/patricksmacchia/2009/02/22/evolutionary-design-and-acyclic-componentization/
crawl-003
refinedweb
1,522
53.1
Yesterday I submitted my first Plugin for GD - .NET/C# of course. It has basic the controls: play/pause/stop/next/prev and displays the title of the track currently playing. I think the hardest part was to get the installer working right. Now that I look back it was quite simple I was just looking at all the wrong places. All I did was take their SamplePlugin project and ripped out 90% of it, and stuff it some basic Winamp control features. One thing I did not like and, for the life of me, could not see how to have the items in the list respond to a single click instead of a double click. Thus, in order to do anything with it you have to double click the items. If Google ever approves of it, and it is put online on their site, I will repost the URL...If your really excited and want it right now, send me some feedback and I can forward you my internal URL for it. The Big Gotcha's: 1. Adding Google's references: GoogleDesktopAPILib, and GoogleDesktopDisplayLib. Make sure you have specified a "Wrapper Assembly Key File" to your plugin project PRIOR to adding those references. Oh yes, that does imply that you have to use "sn" to generate the key file before. You also do not need to have their C++ project included in your plugin solution. Just the references of course. 2. Create a Plugin Installer class: using namespace [System.ComponentModel.RunInstaller( } RegistrationServices regsrv = You can copy that exact class above, no changes are needed as long as it is in the same assembly as your actual plugin. Now, in your installer open the "Custom Actions" and add the "Primary Output" to both the Install and Uninstall sections and be sure to set the "InstallerClass" to true in the properties on the newly added nodes. 3. You dont need to stuff anything in the GAC, unless maybe you have other assemblies which your stuff is using. My entire plugin consist of a single DLL which I allowed for the default install to happen. If you have any problems getting your .NET GD Plug-ins working feel free to use the feedback and I can try to solve some of them with you... Hi! Im new in creating Google Desktop Plugin. Do you have any sample code(in c#) of a Plugin that enables user to simply enter text? If so, kindly email it in motmot@gmail.com. Thanks! Hi! Can you send any sample code(in c#) in kurik@apriorit.com? Hi! Can you send sample code(in c#) of plugin to me(kurik@apriorit.com)? Hi! Can You send any sample code(in c#) of a plugin to me(vladimir.kurka@gmail.com)?
http://weblogs.asp.net/rchartier/archive/2005/08/23/423443.aspx
crawl-002
refinedweb
464
73.07
Tkinter Python GUI Tutorial For Beginners 13- How to embed Matplotlib graph to Tkinter GUI [ad_1] Welcome to this video on Tkinter Python GUI Tutorial For Beginners. This video shows How to embed a Matplotlib graph to your Tkinter GUI. Find the code used in this video here – So What is Tkinter ? Tkinter is the Python interface to the Tk GUI toolkit shipped with Python. In Python you can use the Tkinter module to create simple GUI programs. Tkinter does not always run reliably under IDLE Use IDLE’s editor to write GUI programs, but for best results run the program from the OS command line. Learn Tkinter In easy and simple steps. #ProgrammingKnowledge #Tkinter #PythonGUITutorial! Source [ad_2] Comment List You have just copy the code of matplotlib documentation and I don't think that you have any idea about this . First learn yourself clearly. my text editor says can't invoke button command: application has been destroyed Thanks for the video. It helped a lot in some basic understanding of programming GUI in python. I have one question: the function on_key(event) seems to never be called when program is running. I tried to remove it and it worked perfectly without it. I also placed marker for debugging on one line in that function and I couldn't notice moment when program calls that function. I'm asking because I want to understand the meaning of that function but it seem that it works nothing. Also when I comment canvas.draw() and run program everything stays the same. program works without it, and I couldn't notice the difference. Hi. I have a code that allows me to plot 2 signals from Arduino. I have not being able to embed them into tkinter. All i get is 2 different windows. I appreciate your help. Here is my code. import time import csv import matplotlib matplotlib.use("tkAgg") import matplotlib.pyplot as plt import numpy as np from time import perf_counter import serial ser = serial.Serial('COM4') ser.flushInput() plot_window = 20 y_var = np.array(np.zeros([plot_window])) y_var2 = np.array(np.zeros([plot_window])) print(y_var) print(y_var2) plt.ion() fig, ax = plt.subplots() line, = ax.plot(y_var) line2, = ax.plot(y_var2) while True: try: fig.canvas.toolbar.pack_configure() ser_byte = ser.readline().decode("utf-8").split(',') ser_bytes = ser_byte[0] ser_bytes2 = ser_byte[1] try: decoded_bytes = float(ser_bytes[0:len(ser_bytes)-2]) decoded_bytes2 = float(ser_bytes2[0:len(ser_bytes2)-2]) #print(decoded_bytes) except: continue with open("test_data.csv","a") as f: writer = csv.writer(f,delimiter=",") writer.writerow([time.perf_counter(),decoded_bytes,decoded_bytes2]) y_var = np.append(y_var,decoded_bytes) y_var2 = np.append(y_var2,decoded_bytes2) y_var = y_var[1:plot_window+1] y_var2 = y_var2[1:plot_window+1] line.set_ydata(y_var) line2.set_ydata(y_var2) ax.relim() ax.autoscale_view() fig.canvas.draw() fig.canvas.flush_events() except: print("Keyboard Interrupt") break Very good vedio sir Thank you Hello, Need your help. Could please tell me that can we image as facecolor in matplolib or can we insert image as background in matplolib graph?? Thanks and Regards. Thanks for the video. I had the same mistake as @Netchaiev : "AttributeError: 'FigureCanvasTkAgg' object has no attribute 'manager'" Could you help us, please? Great video! I have just one issue : when I push the "save" button in the toolbar, I get : "AttributeError: 'FigureCanvasTkAgg' object has no attribute 'manager'" I didn't find much about this issue on the internet, somebody knows how to fix this/had the same issue? Your audio quality has deteriorated. Please fix it. You are closing in on 1M subscribers! Nice video First watched this 1st
http://openbootcamps.com/tkinter-python-gui-tutorial-for-beginners-13-how-to-embed-matplotlib-graph-to-tkinter-gui/
CC-MAIN-2021-21
refinedweb
594
61.22
A UDP socket I/O class based on SGIOChannel and plib/net. More... #include <sg_socket_udp.hxx> A UDP socket I/O class based on SGIOChannel and plib/net. Definition at line 49 of file sg_socket_udp.hxx. Create an instance of SGSocketUDP. When calling the constructor you need to provide a host name, and a port number. The convention used by the SGSocketUDP. UDP sockets are a lower level protocol than TCP sockets and are "connectionless" in the sense that either client or server can exist, or not exist, startup, quit, etc. in any order and whenever both ends are alive, the communication succeeds. 38 of file sg_socket_udp.cxx. The close() method is modeled after the close() Unix system call and will close an open device. You should call this method when you are done using your IO class, before it is destructed. Reimplemented from SGIOChannel. Definition at line 189 of file sg_socket_udp.cxx. Definition at line 131 of file sg_socket_udp.hxx. Definition at line 134 of file sg_socket_udp.hxx. Open a channel. Reimplemented from SGIOChannel. Definition at line 54 of file sg_socket_udp 101 of file sg_socket_udp.cxx. The readline() method is similar to read() except that it will stop at the first end of line encountered in the input buffer. Reimplemented from SGIOChannel. Definition at line 118 of file sg_socket_udp.cxx. Set blocking true or false. Definition at line 201 of file sg_socket_udp 160 of file sg_socket_udp.cxx. The writestring() method is a simple wrapper that will calculate the length of a null terminated character array and write it to the output channel. Reimplemented from SGIOChannel. Definition at line 178 of file sg_socket_udp.cxx.
http://simgear.sourceforge.net/doxygen/classSGSocketUDP.html
CC-MAIN-2017-30
refinedweb
274
61.33
Why is swift faster Administrator - 09 March 2017 - 12min Administrator - 09 March 2017 - 12min Introduction Swift was in limelight during last 2 years and was ranked #1 most loved programming language of 2015. It is a general purpose, multi-paradigm, statically typed language. Developed by team led by Chris Lattner at Apple. While introducing Swift in WWDC14 Tim Cook described it using four words which are: In this blog, I will be explaining why and how swift achieves above mentioned qualities. Discovering All the Underlying Swift Power Swift is a strongly typed compiled programming language. This makes it a very safe programming language. Swift is very strict about types, and it verifies that all types are used correctly in the source code. It catches many issues at compile time. Swift is also a static programming language. Its source code is compiled to the assembly code and the assembly code is compiled to the machine code using the LLVM tool. Running native machine code instructions is the fastest way of doing this. In comparison, Java and C# are compiled to a piece of intermediate code, and it needs a virtual machine to run it, or another tool that will translate it into machine instructions. Because Swift doesn’t do this at runtime, it has a very big performance gain. By mixing strongly typed rules and compiling to assembly code, Swift can analyse code very well and perform very good assembly code optimization. Swift is also built to be nice to write, with a pleasant and clean syntax and modern features and types. This unique combination of syntax, powerful features, safety, and performance makes Swift a very amazing programming language. The Compilation The compilation of the Swift source code is quite an interesting process, and it involves several steps. The Swift compiler uses LLVM for optimisation and binary generation. To better understand the entire process, refer to this flow diagram: First, the Swift source code is transformed into an AST (short for Abstract Syntax Tree). Then, it is transformed into SIL (short for Swift Intermediate Language), first into a raw SIL and then into a canonical SIL. After that, it is transformed into LLVM IR (short for Intermediate Representation). In this step, LLVM takes care of the rest. It takes IR, does an optimisation, and produces an assembly and, after that, an executable for a specific architecture. The interesting part in preceding diagram is the steps for generating SIL. It’s a Swift-specific optimisation and it was created specifically for swift. Other programming languages, such as C, don’t do this optimisation before they generate LLVM IR, and they have one less optimisation step. Swiftc There are 2 different Swift compiler tools, swift and swiftc. If you see the help for both the tool using the -h option you will observe they both are swift compilers with almost similar options. The main difference being, the swift tool compiles and executes swift code. If you run it without any arguments, it will launch a REPL and give you the ability to evaluate the Swift code. While The swiftc compiler compiles swift code and produces the result, but it doesn’t execute it. Depending on the option, you can get a binary file, an assembly, an LLVM IR representation, or something else. With swiftc, it’s possible to generate the results for each of those steps. It’s incredibly useful for code optimisation analysis. To see all the available modes, just run xcrun swiftc -h. Now, let’s quickly take a look on them. Swift AST Swiftc has three different options for generating AST. Each of them generates AST with different levels of details. The AST code representation shows us how the Swift compiler sees and analyzes the code: xcrun swiftc -dump-ast main.swift xcrun swiftc -dump-parse main.swift xcrun swiftc -print-ast main.swift The output of -dump-ast contains the maximum details, and it could be hard to analyze. Let’s take a look at the -dump-parse example first: (source_file (var_decl “a” type='<null type>’ let storage_kind=stored) (top_level_code_decl (brace_stmt (pattern_binding_decl (pattern_named ‘a’) (integer_literal_expr type='<null>’ value=10))) This AST code represents the var a = 10 Swift code. Each instruction is parsed into a separate tree node and then put together in a tree representation. You can find more information about Clang’s AST at. SIL The Swift Intermediate Language (SIL) is one of the most useful tools for analyzing Swift code. It contains many details and is very readable and easy to analyze. For generating a SIL, xcrun has two modes; -emit-silgen generates raw SIL and -emit-sil generates canonical SIL: xcrun swiftc -emit-silgen main.swift xcrun swiftc -emit-sil main.swift Raw SIL and canonical SIL are almost the same. Raw SIL is a bit simpler and it doesn’t include the details of private function implementations and some global objects. Let’s take a look at the generated raw SIL: sil_stage raw import Builtin import Swift import SwiftShims // main.a : Swift.Int sil_global [let] @_Tv4main1aSi : $Int … // main sil @main : $@convention(c) (Int32, UnsafeMutablePointer<UnsafeMutablePointer<Int8>>) -> Int32 { … } // main.bye () -> () sil hidden @_TF4main3byeFT_T_ : $@convention(thin) () -> () {… } // static Swift.+ infix (Swift.Int, Swift.Int) -> Swift.Int sil [transparent] [fragile] @_TZFSsoi1pFTSiSi_Si : $@convention(thin) (Int, Int) -> Int A really nice feature of SIL is that it contains comments that explain the generated code. The let a: Int statement would be translated into @_Tv4main1aSi : $Int and we can see this from the comment that stays above the generated SIL: // main.a : Swift.Int sil_global @_Tv4main1aSi : $Int The SIL represents Swift code in a mangled format. The names contain a lot of information about the type, the count of symbols in the name, and so on. Some mangled names can be very long and hard to read, such as _TZvOSs7Process11_unsafeArgvGVSs20UnsafeMutablePointerGS0_VSs4Int8__. We can demangle a name back to its normal notation with the swift-demangle tool. Let’s try to demangle @_Tv4main1aSi and see whether it really translates into main.a : Swift.Int: xcrun swift-demangle _Tv4main1aSi _Tv4main1aSi ---> main.a : Swift.Int If you want to learn more about name mangling, you can read a great post about it written by Mike Ash at. LLVM IR Intermediate Representation (IR) is a more low-level code representation. It is not as human-friendly and readable as SIL. This is because it has more information for the compiler than for humans. We can use IR to compare different programming languages. To get Swift’s IR, use the -emit-ir options, and to get IR for C, we can use clang -emit-llvm: xcrun swiftc -emit-ir main.swift clang -S -emit-llvm main.c -o C-IR.txt Other swiftc options The swiftc compiler is very powerful and has many more modes and options. You can create an assembly, a binary, a linked library, and object files. You can also specify many options, such as an output file with the -o option, optimization -O, -Onone, and many others: xcrun swiftc -emit-assembly main.swift -o assembly Analysing executable files It is very difficult to analyse the assembly code generated by the swiftc compiler. To make our lives easier, we will use a Hopper Disassembler tool to disassemble executable files, generating a piece of pseudocode and analysing it. You can download the free version of Hopper from. The Hopper Disassembler tool can work with binary, executable, and object files. The easiest way of using it is by generating an executable file with the swiftc main.swift command and opening it in Hopper. You can simply drag and drop the main executable file to open it in Hopper. On the left-hand side, you can find all the labels for functions and variables and navigate to them. The search feature is very useful when you are analyzing a big project with many functions. In the center is an assembly code; you can press Alt + Enter to see the pseudocode for the current procedure. It is much easier to analyze high-level pseudocode. We can also compile an application in Xcode and disassemble our SimpleApp.app in Hopper. This allows us to analyze very large and complex applications as well. So, that’s all on compilation process for a swift, I hope you did get the reason behind Tim Cook calling Swift a Fast, Safe and Interactive language. I guess I missed Modern, because I reckon that’s a topic for another writing.
https://www.talentica.com/blogs/why-is-swift-faster/
CC-MAIN-2021-04
refinedweb
1,406
64.71
Hi want to create a grid 5 by 5 and fill it randomnly with number using javascript. Can someone help? Hi want to create a grid 5 by 5 and fill it randomnly with number using javascript. Can someone help? Do you have any code to work with as of yet? I am thinking that you can create a grid using a table or div element, assign each cell a unique id from 0-24. then, in your JavaScript function, reference each element ID within a for loop and then generate the random number using the random() method and assign that value to the innerHTML property of the element. use this formula to get a random number from 1-10. Math.floor((Math.random()*10)+1); ok forget the grid. lets generate it as a 2D array. I have done this but its not a 2D array. I want to put it in a 2 Dimensional array. Can i know how to proceed? var string=""; for (var i=0;i<10;++i){ for(var j=0;j<10;++j){ var first =generatecase(0,100000); if((first %2)==0) { string= string+ " "+generate(0,9); } else{ var second=generate(0,100000); if((second%2)==0) {string=string+ " "+ "+";} else {string=string+ " "+ "-" ;} } } string=string+"<br>"; } document.write(string); function generate(x,y) {return Math.floor(Math.random() * (x - y + 1)) + y;} in actionscript I would make it with an array formatted to be understandable eg. var grid = new Array(1,2,3,4, 5,6,7,8, 9,10,11,12, 13,14,15,16, 17,18,19,20, 21,22,23,24); Once you see that format its much easier to grasp how to make it up, i just done random numbers here since you said afterwards you wanted random not a grid: <html> <head> <script type='text/javascript'> function generateRand(){return Math.floor(Math.random()*500);} var perRow = 4; var numRows = 6; var grid = new Array(); grid['x'] = new Array(); grid['y'] = new Array(); for (var i=0; i<numRows; i++){ for (var ii=0; ii<perRow; ii++){ var iii = 0; if(i == 0){ }else{ iii += (perRow*i); } iii += ii; grid['x'][iii] = generateRand(); grid['y'][iii] = generateRand(); } } console.log(grid); console.log(grid['x']); console.log(grid['y']); var obj = new Object(); obj.x = grid['x'][0]; obj.y = grid['y'][0]; console.log(obj); </script> </head> <body> </body> </html> Edited by Biiim: typo var a = new Array(10); for (i = 0; i < 10; i++) { for (j = 0; j < 10; j++) { a[i,j] = 1; document.write(a[i,j]); } } Ok i manage to write it in 2D array. Now i want to draw a grid of size 10 by 10 and populate it using this 2D array. how can i do this? the code above is for my 2D array. it will display 1 everywhere in the grid. Anyone can tell me how to proceed? i want to do this in javascript. Edited by techyworld Ah.. I had just saw this updated thread, but while offline, I had worked on a sample in which a dynamic HTML table is created and then populated by random numbers. In case you still want to see it, take a look at this sample: How to Create a Dynamic Table with JavaScript What the demo I worked on does is it creates the table based on the values of two variables in the JavaScript function and populates the cells with random numbers that you also define in two variables. results displayed in a table...for this example the range is 1-10... Edited by JorgeM @techyworld, Your script is completely wrong. It does NOT create a 2D array but rather create all-undefined-value array size of 10. But then you wrongly assign a value of 1 using an invalid index (not a number). Because JavaScript always trys to fix the user script, it insteads uses your second argument (j) from [i,j] as index. var a = new Array(3); // created [undefined, undefined, undefined] a[2,4] = 1; // modify it to [undefined, undefined, undefined, undefined, 1] a[3,1] = 2; // modify it to [undefined, 2, undefined, undefined, 2] A proper to create a 2D array is to use iteration. var a = new Array(3); // created [undefined, undefined, undefined] for (var i=0; i<a.length; i++) { a[i] = new Array(2); } /* now each iteration when i is 0, 1, and 2 will be as follows: after the i=0, a becomes [[undefined, undefined], undefined, undefined] after the i=1, a becomes [[undefined, undefined], [undefined, undefined], undefined] after the i=2, a becomes [[undefined, undefined], [undefined, undefined], [undefined, undefined]] */ Below is a quick & dirty implementation of a function that takes 4 variables -- row number, column number, minimum random value, and maximum random value -- instead of fixing most everything as constants, and return a 2D array. <script type="text/javascript"> /***** * Return a 2D array size of the given number of rows & columns. The values filled * inside the array are random values between minVal and maxVal -- [minVal, maxVal). * If minVal is not given, the default value is 0. If the given minVal is greater * than maxVal, the minimum value used will come from maxVal and the maximum value * used will come from minVal. Return null if any of the argument is invalid. */ function generate2DArrayWithRandomValue(rows, columns, maxVal, minVal) { if (isNaN(rows) || rows<1 || // not valid row value isNaN(columns) || columns<1 || // not valid column value isNaN(maxVal)) { // not valid maximum value return null; } minVal = isNaN(minVal) ? 0 : minVal; var output = new Array(rows); // create an array with total row number for (var r=0; r<rows; r++) { output[r] = new Array(columns); // create 2nd dimension with total column number for (var c=0; c<columns; c++) { output[r][c] = getRandomNumber(minVal, maxVal); } } return output; // done } // generate2DArrayWithRandomValue /***** * Return an integer value between min and max. If min is less than or equal to * max, return [min, max). If min is equal to max, return the value of min/max. * If min is greater than max, return [max, min). * Expecting min & max are numbers. */ function getRandomNumber(min, max) { var diff = max-min; var range = Math.floor(Math.random()*diff); return (min+range); } // getRandomNumber /***** * Display a given array (supposely 2D) using table format inside the given * div element ID. * You would need to update this function if you want to change the display * of the array. */ function displayArrayAsTable(outputId, anArray) { var el = document.getElementById(outputId); var" if(anArray instanceof Array) { // row is OK for (var r=0; r<anArray.length; r++) { // go through each row output += "<tr>" if (anArray[r] instanceof Array) { for (var c=0; c<anArray[r].length; c++) { output += "<td style=\""+tdStyle+"\">"+anArray[r][c]+"</td>" } } else { // not a 2D array, so it is simply an element output += "<td style=\""+tdStyle+"\">"+anArray[r]+"</td>" } output += "</tr>" } } else { output += "<tr><td>"+anArray+"</td></tr>" } output += "</table>" el.innerHTML = output; } } // displayArrayAsTable </script> PS: It is a bad idea to start your programming experience with JavaScript. The problem is that the language does NOT help a programmer/developer learn how to properly implement an algorithm because it attempts to correct the programmer/developer wrong logic/syntax. If you want to start your programming experience, start with either lower level language as C or C++ or a bit higher level language as Java (not the same as JavaScript), python, small talk, or ruby (not perl because the language is a bit messy). PSS: The level of language does not mean its difficulty but rather the ability to access the computer/operating system functionality/hardware it is running on. Edited by Taywin ...
https://www.daniweb.com/programming/web-development/threads/446190/fill-with-random-number
CC-MAIN-2018-13
refinedweb
1,270
54.12
Oliver Deakin wrote: > Hi Alexey, > > ok, Ive recreated your problem using the latest snapshot and VME. > Essentially the code at > modules/kernel/src/main/java/java/lang/String.java is the same as that > in the VME kernel.jar. Looking in there (these calls can also be seen if > the test is run within a debugger), we see that the replaceFirst(String, > String) implementation is: > > public String replaceFirst(String expr, String substitute) { > return Pattern.compile(expr).matcher(this).replaceFirst(substitute); > } > > Unfortunately the implementation of Pattern at > modules/regex/src/main/java/java/util/regex/Pattern.java is only a stub > (as HARMONY-39 has not yet been accepted into the Harmony SVN > repository) and as such just returns null. Thus when we try to > dereference the return from Pattern.compile(expr) we receive a > NullPointerException. Once the regex in HARMONY-39 is moved into SVN > this should go away. > > >? Why wasn't it that way to start? geir > > > Alexey Petrenko wrote: >> We got problem with Harmony on IBM VM on Windows. >> java.lang.String.replaceFirst throws NPE. >> >> Here is the testcase: >> public class Test { >> public static void main(String args[]) { >> String xx = "test"; >> xx = xx.replaceFirst("t","z"); >> } >> } >> >> Here is the stack trace: >> C:\Work\Harmony\Sources\Harmony\deploy\jre\bin>java Test >> Exception in thread "main" java.lang.NullPointerException >> at java.lang.String.replaceFirst(String.java:1642) >> at Test.main(Test.java:4) >> >> Since IBM VM is not an OpenSource I can not check java.lang.String for >> the cause of this problem :( >> >> Can we ask IBM guys somehow to fix this issue? >> >> -- >> Alexey A. Petrenko >> Intel Middleware Products Division >> >
http://mail-archives.apache.org/mod_mbox/harmony-dev/200602.mbox/%3C43FC0425.40903@pobox.com%3E
CC-MAIN-2018-22
refinedweb
271
51.75
In NSS 3.11, when we removed FORTEZZA support, three FORTEZZA cipher suites were removed from the cipherSuites array in lib/ssl/ssl3con.c, but the ssl_V3_SUITES_IMPLEMENTED macro (the size of that array) in lib/ssl/sslimpl.h is not updated. So ssl_V3_SUITES_IMPLEMENTED is now off by 3, resulting in three zero entries at the end of the cipherSuites array. I believe those three zero entries are harmless, hence the "trivial" severity of this bug. But it is best to fix this on the NSS_3_11_BRANCH the first chance we have. Created attachment 205785 [details] [diff] [review] Patch for NSS_3_11_BRANCH I fixed this bug on the NSS trunk (NSS 3.12) with a patch (attachment 205783 [details] [diff] [review]) in bug 236245. Comment on attachment 205785 [details] [diff] [review] Patch for NSS_3_11_BRANCH Wan-Teh, there's a discrepancy between this patch and the one you made for the trunk, for the case when NSS_ENABLE_ECC is defined. In this patch, you're decreasing the value by 3, from 40 to 37, but in the patch for the trunk, you increased it by 3, from 40 to 43. Does the trunk have 6 more ECC ciphersuites than 3.11 did? or ?? > #ifdef NSS_ENABLE_ECC >-#define ssl_V3_SUITES_IMPLEMENTED 40 >+#define ssl_V3_SUITES_IMPLEMENTED 37 > #else >-#define ssl_V3_SUITES_IMPLEMENTED 26 >+#define ssl_V3_SUITES_IMPLEMENTED 23 > #endif /* NSS_ENABLE_ECC */ Nelson: yes, Douglas added 6 new ECC cipher suites to the trunk in that patch, resulting in a net change of +3 (+6 -3). In hindsight, I should not have included the fix for this bug in that patch because it is confusing if you just look at the CVS commit comment. Comment on attachment 205785 [details] [diff] [review] Patch for NSS_3_11_BRANCH Thanks for the explanation. I checked in the patch on the NSS_3_11_BRANCH for NSS 3.11.1. Checking in sslimpl.h; /cvsroot/mozilla/security/nss/lib/ssl/sslimpl.h,v <-- sslimpl.h new revision: 1.42.2.1; previous revision: 1.42 done
https://bugzilla.mozilla.org/show_bug.cgi?id=319240
CC-MAIN-2017-43
refinedweb
320
72.76
The Jamstack is a modern web development architecture based on client-side JavaScript, reusable APIs, and prebuilt Markup. The key aspects of a Jamstack application are the following: - The entire app runs on a CDN (or ADN). CDN stands for Content Delivery Network and an ADN is an Application Delivery Network. - Everything lives in Git. - Automated builds run with a workflow when developers push the code. - There’s Automatic deployment of the prebuilt markup to the CDN/ADN. - Reusable APIs make hasslefree integrations with many of the services. To take a few examples, Stripe for the payment and checkout, Mailgun for email services, etc. We can also write custom APIs targeted to a specific use-case. We will see such examples of custom APIs in this article. - It’s practically Serverless. To put it more clearly, we do not maintain any servers, rather make use of already existing services (like email, media, database, search, and so on) or serverless functions. In this article, we will learn how to build a Jamstack application that has: - A global data store with GraphQL support to store and fetch data with ease. We will use Fauna to accomplish this. - Serverless functions that also act as the APIs to fetch data from the Fauna data store. We will use Netlify serverless functions for this. - We will build the client side of the app using a Static Site Generator called Gatsbyjs. - Finally we will deploy the app on a CDN configured and managed by Netlify CDN. So, what are we building today?So, what are we building today? We all love shopping. How cool would it be to manage all of our shopping notes in a centralized place? So we’ll be building an app called ‘shopnote’ that allows us to manage shop notes. We can also add one or more items to a note, mark them as done, mark them as urgent, etc. At the end of this article, our shopnote app will look like this, TL;DRTL;DR We will learn things with a step-by-step approach in this article. If you want to jump into the source code or demonstration sooner, here are links to them. - You can access the shop note demo from here: - All the source code used in this article is in my GitHub repo. Feel free to follow it, as I keep updating the source code frequently. Set up FaunaSet up Fauna Fauna is the data API for client-serverless applications. If you are familiar with any traditional RDBMS, a major difference with Fauna would be, it is a relational NOSQL system that gives all the capabilities of the legacy RDBMS. It is very flexible without compromising scalability and performance. Fauna supports multiple APIs for data-access, - GraphQL: An open source data query and manipulation language. If you are new to the GraphQL, you can find more details from here, - Fauna Query Language (FQL): An API for querying Fauna. FQL has language specific drivers which makes it flexible to use with languages like JavaScript, Java, Go, etc. Find more details of FQL from here. In this article we will explain the usages of GraphQL for the ShopNote application. First thing first, sign up using this URL. Please select the free plan which is with a generous daily usage quota and more than enough for our usage. Next, create a database by providing a database name of your choice. I have used shopnotes as the database name. After creating the database, we will be defining the GraphQL schema and importing it into the database. A GraphQL schema defines the structure of the data. It defines the data types and the relationship between them. With schema we can also specify what kind of queries are allowed. At this stage, let us create our project folder. Create a project folder somewhere on your hard drive with the name, shopnote. Create a file with the name, shopnotes.gql with the following content: type ShopNote { name: String! description: String updatedAt: Time items: [Item!] @relation } type Item { name: String! urgent: Boolean checked: Boolean note: ShopNote! } type Query { allShopNotes: [ShopNote!]! } Here we have defined the schema for a shopnote list and item, where each ShopNote contains name, description, update time and a list of Items. Each Item type has properties like, name, urgent, checked and which shopnote it belongs to. Note the @relation directive here. You can annotate a field with the @relation directive to mark it for participating in a bi-directional relationship with the target type. In this case, ShopNote and Item are in a one-to-many relationship. It means, one ShopNote can have multiple Items, where each Item can be related to a maximum of one ShopNote. You can read more about the @relation directive from here. More on the GraphQL relations can be found from here. As a next step, upload the shopnotes.gql file from the Fauna dashboard using the IMPORT SCHEMA button, Upon importing a GraphQL Schema, FaunaDB will automatically create, maintain, and update, the following resources: - Collections for each non-native GraphQL Type; in this case, ShopNote and Item. - Basic CRUD Queries/Mutations for each Collection created by the Schema, e.g. createShopNote allShopNotes; each of which are powered by FQL. - For specific GraphQL directives: custom Indexes or FQL for establishing relationships (i.e. @relation), uniqueness ( @unique), and more! Behind the scene, Fauna will also help to create the documents automatically. We will see that in a while. Fauna supports a schema-free object relational data model. A database in Fauna may contain a group of collections. A collection may contain one or more documents. Each of the data records are inserted into the document. This forms a hierarchy which can be visualized as: Here the data record can be arrays, objects, or of any other supported types. With the Fauna data model we can create indexes, enforce constraints. Fauna indexes can combine data from multiple collections and are capable of performing computations. At this stage, Fauna already created a couple of collections for us, ShopNote and Item. As we start inserting records, we will see the Documents are also getting created. We will be able view and query the records and utilize the power of indexes. You may see the data model structure appearing in your Fauna dashboard like this in a while, Point to note here, each of the documents is identified by the unique ref attribute. There is also a ts field which returns the timestamp of the recent modification to the document. The data record is part of the data field. This understanding is really important when you interact with collections, documents, records using FQL built-in functions. However, in this article we will interact with them using GraphQL queries with Netlify Functions. With all these understanding, let us start using our Shopenotes database that is created successfully and ready for use. Let us try some queriesLet us try some queries Even though we have imported the schema and underlying things are in place, we do not have a document yet. Let us create one. To do that, copy the following GraphQL mutation query to the left panel of the GraphQL playground screen and execute. mutation { createShopNote(data: { name: "My Shopping List" description: "This is my today's list to buy from Tom's shop" items: { create: [ { name: "Butther - 1 pk", urgent: true } { name: "Milk - 2 ltrs", urgent: false } { name: "Meat - 1lb", urgent: false } ] } }) { _id name description items { data { name, urgent } } } } Note, as Fauna already created the GraphQL mutation classes in the background, we can directly use it like, createShopNote. Once successfully executed, you can see the response of a ShopNote creation at the right side of the editor. The newly created ShopNote document has all the required details we have passed while creating it. We have seen ShopNote has a one-to-many relation with Item. You can see the shopnote response has the item data nested within it. In this case, one shopnote has three items. This is really powerful. Once the schema and relation are defined, the document will be created automatically keeping that relation in mind. Now, let us try fetching all the shopnotes. Here is the GraphQL query: query { allShopNotes { data { _id name description updatedAt items { data { name, checked, urgent } } } } } Let’s try the query in the playground as before: Now we have a database with a schema and it is fully operational with creating and fetch functionality. Similarly, we can create queries for adding, updating, removing items to a shopnote and also updating and deleting a shopnote. These queries will be used at a later point in time when we create the serverless functions. If you are interested to run other queries in the GraphQL editor, you can find them from here, Create a Server Secret KeyCreate a Server Secret Key Next, we need to create a secured server key to make sure the access to the database is authenticated and authorized. Click on the SECURITY option available in the FaunaDB interface to create the key, like so, On successful creation of the key, you will be able to view the key’s secret. Make sure to copy and save it somewhere safe. We do not want anyone else to know about this key. It is not even a good idea to commit it to the source code repository. To maintain this secrecy, create an empty file called .env at the root level of your project folder. Edit the .env file and add the following line to it (paste the generated server key in the place of, <YOUR_FAUNA_KEY_SECRET>). FAUNA_SERVER_SECRET=<YOUR_FAUNA_KEY_SECRET> Add a .gitignore file and write the following content to it. This is to make sure we do not commit the .env file to the source code repo accidentally. We are also ignoring node_modules as a best practice. .env We are done with all that had to do with Fauna’s setup. Let us move to the next phase to create serverless functions and APIs to access data from the Fauna data store. At this stage, the directory structure may look like this, Set up Netlify Serverless FunctionsSet up Netlify Serverless Functions Netlify is a great platform to create hassle-free serverless functions. These functions can interact with databases, file-system, and in-memory objects. Netlify functions are powered by AWS Lambda. Setting up AWS Lambdas on our own can be a fairly complex job. With Netlify, we will simply set a folder and drop our functions. Writing simple functions automatically becomes APIs. First, create an account with Netlify. This is free and just like the FaunaDB free tier, Netlify is also very flexible. Now we need to install a few dependencies using either npm or yarn. Make sure you have nodejs installed. Open a command prompt at the root of the project folder. Use the following command to initialize the project with node dependencies, npm init -y Install the netlify-cli utility so that we can run the serverless function locally. npm install netlify-cli -g Now we will install two important libraries, axios and dotenv. axios will be used for making the HTTP calls and dotenv will help to load the FAUNA_SERVER_SECRET environment variable from the .env file into process.env. yarn add axios dotenv Or: npm i axios dotenv Create serverless functionsCreate serverless functions Create a folder with the name, functions at the root of the project folder. We are going to keep all serverless functions under it. Now create a subfolder called utils under the functions folder. Create a file called query.js under the utils folder. We will need some common code to query the data store for all the serverless functions. The common code will be in the query.js file. First we import the axios library functionality and load the .env file. Next, we export an async function that takes the query and variables. Inside the async function, we make calls using axios with the secret key. Finally, we return the response. // query.js const axios = require("axios"); require("dotenv").config(); module.exports = async (query, variables) => { const result = await axios({ url: "", method: "POST", headers: { Authorization: `Bearer ${process.env.FAUNA_SERVER_SECRET}` }, data: { query, variables } }); return result.data; }; Create a file with the name, get-shopnotes.js under the functions folder. We will perform a query to fetch all the shop notes. // get-shopnotes.js const query = require("./utils/query"); const GET_SHOPNOTES = ` query { allShopNotes { data { _id name description updatedAt items { data { _id, name, checked, urgent } } } } } `; exports.handler = async () => { const { data, errors } = await query(GET_SHOPNOTES); if (errors) { return { statusCode: 500, body: JSON.stringify(errors) }; } return { statusCode: 200, body: JSON.stringify({ shopnotes: data.allShopNotes.data }) }; }; Time to test the serverless function like an API. We need to do a one time setup here. Open a command prompt at the root of the project folder and type: netlify login This will open a browser tab and ask you to login and authorize access to your Netlify account. Please click on the Authorize button. Next, create a file called, netlify.toml at the root of your project folder and add this content to it, [build] functions = "functions" [[redirects]] from = "/api/*" to = "/.netlify/functions/:splat" status = 200 This is to tell Netlify about the location of the functions we have written so that it is known at the build time. Netlify automatically provides the APIs for the functions. The URL to access the API is in this form, /.netlify/functions/get-shopnotes which may not be very user-friendly. We have written a redirect to make it like, /api/get-shopnotes. Ok, we are done. Now in command prompt type, netlify dev By default the app will run on localhost:8888 to access the serverless function as an API. Open a browser tab and try this URL,: Congratulations!!! You have got your first serverless function up and running. Let us now write the next serverless function to create a ShopNote. This is going to be simple. Create a file named, create-shopnote.js under the functions folder. We need to write a mutation by passing the required parameters. //create-shopnote.js const query = require("./utils/query"); const CREATE_SHOPNOTE = ` mutation($name: String!, $description: String!, $updatedAt: Time!, $items: ShopNoteItemsRelation!) { createShopNote(data: {name: $name, description: $description, updatedAt: $updatedAt, items: $items}) { _id name description updatedAt items { data { name, checked, urgent } } } } `; exports.handler = async event => { const { name, items } = JSON.parse(event.body); const { data, errors } = await query( CREATE_SHOPNOTE, { name, items }); if (errors) { return { statusCode: 500, body: JSON.stringify(errors) }; } return { statusCode: 200, body: JSON.stringify({ shopnote: data.createShopNote }) }; }; Please give your attention to the parameter, ShopNotesItemRelation. As we had created a relation between the ShopNote and Item in our schema, we need to maintain that while writing the query as well. We have de-structured the payload to get the required information from the payload. Once we got those, we just called the query method to create a ShopNote. Alright, let’s test it out. You can use postman or any other tools of your choice to test it like an API. Here is the screenshot from postman. Great, we can create a ShopNote with all the items we want to buy from a shopping mart. What if we want to add an item to an existing ShopNote? Let us create an API for it. With the knowledge we have so far, it is going to be really quick. Remember, ShopNote and Item are related? So to create an item, we have to mandatorily tell which ShopNote it is going to be part of. Here is our next serverless function to add an item to an existing ShopNote. //add-item.js const query = require("./utils/query"); const ADD_ITEM = ` mutation($name: String!, $urgent: Boolean!, $checked: Boolean!, $note: ItemNoteRelation!) { createItem(data: {name: $name, urgent: $urgent, checked: $checked, note: $note}) { _id name urgent checked note { name } } } `; exports.handler = async event => { const { name, urgent, checked, note} = JSON.parse(event.body); const { data, errors } = await query( ADD_ITEM, { name, urgent, checked, note }); if (errors) { return { statusCode: 500, body: JSON.stringify(errors) }; } return { statusCode: 200, body: JSON.stringify({ item: data.createItem }) }; }; We are passing the item properties like, name, if it is urgent, the check value and the note the items should be part of. Let’s see how this API can be called using postman, As you see, we are passing the id of the note while creating an item for it. We won’t bother writing the rest of the API capabilities in this article, like updating, deleting a shop note, updating, deleting items, etc. In case, you are interested, you can look into those functions from the GitHub Repository. However, after creating the rest of the API, you should have a directory structure like this, We have successfully created a data store with Fauna, set it up for use, created an API backed by serverless functions, using Netlify Functions, and tested those functions/routes. Congratulations, you did it. Next, let us build some user interfaces to show the shop notes and add items to it. To do that, we will use Gatsby.js (aka, Gatsby) which is a super cool, React-based static site generator. The following section requires you to have basic knowledge of ReactJS. If you are new to it, you can learn it from here. If you are familiar with any other user interface technologies like, Angular, Vue, etc feel free to skip the next section and build your own using the APIs explained so far. Set up the User Interfaces using GatsbySet up the User Interfaces using Gatsby We can set up a Gatsby project either using the starter projects or initialize it manually. We will build things from scratch to understand it better. Install gatsby-cli globally. npm install -g gatsby-cli Install gatsby, react and react-dom yarn add gatsby react react-dom Edit the scripts section of the package.json file to add a script for develop. "scripts": { "develop": "gatsby develop" } Gatsby projects need a special configuration file called, gatsby-config.js. Please create a file named, gatsby-config.js at the root of the project folder with the following content, module.exports = { // keep it empty } Let’s create our first page with Gatsby. Create a folder named, src at the root of the project folder. Create a subfolder named pages under src. Create a file named, index.js under src/pages with the following content: import React, { useEffect, useState } from 'react'; export default () => { const [loading, setLoading ] = useState(false); const [shopnotes, setShopnotes] = useState(null); return ( <> <h1>Shopnotes to load here...</h1> </> ) } Let’s run it. We generally need to use the command gatsby develop to run the app locally. As we have to run the client side application with netlify functions, we will continue to use, netlify dev command. netlify dev That’s all. Try accessing the page at. You should see something like this, Gatsby project build creates a couple of output folders which you may not want to push to the source code repository. Let us add a few entries to the .gitignore file so that we do not get unwanted noise. Add .cache, node_modules and public to the .gitignore file. Here is the full content of the file: .cache public node_modules *.env At this stage, your project directory structure should match with the following: Thinking of the UI componentsThinking of the UI components We will create small logical components to achieve the ShopNote user interface. The components are: - Header: A header component consists of the Logo, heading and the create button to create a shopnote. - Shopenotes: This component will contain the list of the shop note ( Notecomponent). - Note: This is individual notes. Each of the notes will contain one or more items. - Item: Each of the items. It consists of the item name and actions to add, remove, edit an item. You can see the sections marked in the picture below: Install a few more dependenciesInstall a few more dependencies We will install a few more dependencies required for the user interfaces to be functional and look better. Open a command prompt at the root of the project folder and install these dependencies, yarn add bootstrap lodash moment react-bootstrap react-feather shortid Lets load all the Shop NotesLets load all the Shop Notes We will use the Reactjs useEffect hook to make the API call and update the shopnotes state variables. Here is the code to fetch all the shop notes. useEffect(() => { axios("/api/get-shopnotes").then(result => { if (result.status !== 200) { console.error("Error loading shopnotes"); console.error(result); return; } setShopnotes(result.data.shopnotes); setLoading(true); }); }, [loading]); Finally, let us change the return section to use the shopnotes data. Here we are checking if the data is loaded. If so, render the Shopnotes component by passing the data we have received using the API. return ( <div className="main"> <Header /> { loading ? <Shopnotes data = { shopnotes } /> : <h1>Loading...</h1> } </div> ); You can find the entire index.js file code from here The index.js file creates the initial route( /) for the user interface. It uses other components like, Shopnotes, Note and Item to make the UI fully operational. We will not go to a great length to understand each of these UI components. You can create a folder called components under the src folder and copy the component files from here. Finally, the index.css file Now we just need a css file to make things look better. Create a file called index.css under the pages folder. Copy the content from this CSS file to the index.css file. import 'bootstrap/dist/css/bootstrap.min.css'; import './index.css' That’s all. We are done. You should have the app up and running with all the shop notes created so far. We are not getting into the explanation of each of the actions on items and notes here not to make the article very lengthy. You can find all the code in the GitHub repo. At this stage, the directory structure may look like this, A small exerciseA small exercise I have not included the Create Note UI implementation in the GitHib repo. However, we have created the API already. How about you build the front end to add a shopnote? I suggest implementing a button in the header, which when clicked, creates a shopnote using the API we’ve already defined. Give it a try! Let’s DeployLet’s Deploy All good so far. But there is one issue. We are running the app locally. While productive, it’s not ideal for the public to access. Let’s fix that with a few simple steps. Make sure to commit all the code changes to the Git repository, say, shopnote. You have an account with Netlify already. Please login and click on the button, New site from Git. Next, select the relevant Git services where your project source code is pushed. In my case, it is GitHub. Browse the project and select it. Provide the configuration details like the build command, publish directory as shown in the image below. Then click on the button to provide advanced configuration information. In this case, we will pass the FAUNA_SERVER_SECRET key value pair from the .env file. Please copy paste in the respective fields. Click on deploy. You should see the build successful in a couple of minutes and the site will be live right after that. In SummaryIn Summary To summarize: - The Jamstack is a modern web development architecture based on client-side JavaScript, reusable APIs, and prebuilt Markup. - 70% – 80% of the features that once required a custom back-end can now be done either on the front end or there are APIs, services to take advantage of. - Fauna provides the data API for the client-serverless applications. We can use GraphQL or Fauna’s FQL to talk to the store. - Netlify serverless functions can be easily integrated with Fauna using the GraphQL mutations and queries. This approach may be useful when you have the need of custom authentication built with Netlify functions and a flexible solution like Auth0. - Gatsby and other static site generators are great contributors to the Jamstack to give a fast end user experience. Thank you for reading this far! Let’s connect. You can @ me on Twitter (@tapasadhikary) with comments, or feel free to follow. Hi! Great article! I Just want to ask: what are the advantages here to use Gatsby instead of pure React? I always thought of Gatsby as a tool useful to write static sites, for example a blog where you write a new page, push to git, with CI/CD you build and than deploy to the CDN. Here instead we are using Gatsby to create something similar to a Webapp. Thanks for reading and commenting. From the ShopNote app perspective, the difference is not much. As it is a single page application which just fetches data at the run time. Now if the similar app is part of a bigger umbrella where you want to precompile the pages upfront and load the initial pages as soon as possible from a CDN, it will make the difference for sure. This article uses gatsby more from a kick-start technology perspective and as an introduction. Thanks for asking. Hi! Great article! I think there are missing fields in the note creation function, const { name, items } = JSON.parse(event.body); description and updatedAt fields should also be included in here. Yes, we can include those too if required.
https://css-tricks.com/how-to-create-a-client-serverless-jamstack-app-using-netlify-gatsby-and-fauna/
CC-MAIN-2021-17
refinedweb
4,247
66.64
Ping Test Easy 330 Yexyxu Ping Test Easy 330 Yexyxu Description D O W N L O A D Ping Test Easy 330 Yexyxu Permanent free, handy, powerful, visual network speed test utility for system administrator to check network speed and connection, this simple program is..Download Ping Test Easy 9.43 for Windows. Ping Test Easy is an easy to use utility that allows you to test your connection and your ping..Free Download Ping Test Easy for windows. Ping Test Easy 3.38- Ping Test Easy 3.36- Ping Test Easy 3.35- Ping Test Easy 3.32- Ping Test Easy 3.30- Ping .Ping Test Easy, free and safe download. Ping Test Easy latest version: Quickly check on your network connection. For the benefit of the uninitiated, pinging is .Ping Test Easy 3.30. Logiciel. WinPing 1.6.4104 - Test your Internet connection with a ping function. Logiciel. Cook s Country From America s Test Kitchen .PingPlotter Standard perpetually collects information about your network. Sharing makes it easy to show others how your network is performing. PingPlotter Professional tests hundreds of targets at once and includes tools for broadcasting .PingPlotter Pro tests hundreds of targets at once. Summary Named configurations make it easy to apply different packet settings to different targets. PRO..Ping Test Easy does the same job as paid software in half the time and is Ping Test Easy 3.35 Ping Test Easy 3.32 Ping Test Easy 3.30 Ping .Download File. File: easy tuner 30 keygen.torrent flash guitar tuner - very easy, (1MB ), 1445, 8602 Ping Test easy 3.30, (133.89kB ), 4019, 8642. Registry .even easier for managers and technicians 3.30”. 2.00”. 6.640”. TM. Network Test Features. Link Tests. • Verify Link Connection Configurable Ping Test..Telerik Test serial numbers, cracks and keygens are presented here. No registration is needed. Portable Ping Test Easy 2 serial keygen ·- Test Drive 5 key generator Ping Test Easy 3.30 key generator ·- Test Drive Unlimited .Ping Test Easy 3.30 6 torrent download locations. Download Direct Ping Test Easy 3.30: Sponsored Link. monova.org Ping Test Easy 3.30 Software: 1 day..Link Tests. • Configurable Ping Tests. • Trace Route. • Device Emulation Test Fiber Links*. • Optical The PingerPros extensive features make it even easier for 3.30”. 2.00”. 6.640”. PRO70. PingerPro 70 Copper. Retail List Price: $599.00..Ping Test Easy 4.06 - Free software downloads and software reviews (2011-09-28)- Ping Test Easy 3.30 - Free software downloads and .Starting with BBPE 3.30, you can have multiple BBNETs print out and complete this list before installing Big Brother so you have the information easily .. (If there are no test directives, Big Brother will only ping the host and .Ping plotter pro 5.2.8 crack license key free download. Ping plotter pro 5.2.8 Pingplotter pro 3.30.4 crack keygen . Download 341mac Como descargar e instalar los programas ping plotter, ping test easy, free ip scanner. Privacy eraser pro .To test support response times, a ticket was sent in asking for This will ensure that all readers have access to commands used and are able to replicate tests easily. Intel(R) Xeon(R) CPU E3-1230 V2 @ 3.30GHz stepping : 9 cpu MHz root@hostigation:~/benchmark# bash ping.sh PING google.com .I can run every game without any lags and often the lowest ping of all players. Intel Core i5-4590 CPU @ 3.30Ghz I cant test no.1 easily through comments, but there is something you can do to test the ping you have in .Playing ping pong all night long, everythings on me and then hazy. Chanel this, Chanel that, hell yeah. All .File Sharing Made Easy! / Nakido. Analysis Hong Kong, 5,408, 3.30%, 3.70%. Japan, 7,003 milliseconds. Also a time of 109 ms, is recorded in a ping test..Rechercher plus Ping Test Easy 3.30 WinPing 1.6.4104 - Test your Internet connection with a ping function Logiciel. Minceraft Test map (a bit easy) . a power spec with an intel(R) core(TM) i7-5820K cpu @3.30GHz and what results do you get at [pingtest.net] ?.Easily Find DivX Subtitles For Your Movies DivX Subtitles Search Engine all4divx.com. Analysis United Kingdom, 52,372, 3.30%, 1.90% A time of 114 ms, is recorded in a ping test, also its average full page load time is 2828 milliseconds..namespace omaha {. class PingTest : public testing::Test {. protected: virtual void SetUp() {. RegKey::DeleteKey(USER_REG_UPDATE _T("\\PersistedPings"))-. }..It allows you to ping any type of server. I have run some test just to see how bad the pings where Then after Running a Traceroute to the GAME server I found that the ping times went from just . 7 219.158.3.30 60 msec 60 msec 56 msec.Version 3.30 The Web Configurator allows easy ZyWALL setup and management using an Type ping -6 ipv6.google.com in a Command Prompt to test..Been trying to get it to work since 3.30pm - close to throwing laptop thru COMPLEX MEDICAL EQUIPMENT, REAGENTS, TESTS, EASY TO .It turns out to be quite easy to determine. Just open the Command Prompt window and type in "ping -f -l 1472 172.16.0.1" (or your router IP) .Update EssentialPIM 2.51 - Update ReNamer 5.25 - Update Paint.NET 3.30 - Update KeePass 1.11 . Update Ping Test Easy 3.17 - Update Omziff 3.0.9.5.4team outlook duplicate remover 3.30.0138 serial numbers, cracks and keygens are presented here. Ping Test Easy 3.30 key generator..Next step is ping test 10ms ping, and 2ms jitter CPU AM3+ AMD FX-8300, 3.30GHz BOX Black Edition 32nm. MB AM3+ 970 Gigabyte .Set/Get command of HNAP 4. DWM-152/156 . Fix in Russia PPTP and Russia PPPoE mode,ping test function will cause DUT reboot unexpectedly 6.Fix when .Added "Total" line to the "Bandwidth Test" panel to show the total of the Tx and Rx values .. Added field to specify the ping timeout in the Ping Test panel. . the eMax setting of older radios (with version 3.30 firmware) from being set properly..Ping Test – Used to test connectivity between other IP aware devices. TFTP Server .. easily diagnose link fault problems if they occur. Fig. 3.16. Mode: Used to . with another device. Fig. 3.30. Run Again: Used to perform the loopback test..easier implementation of fail-over scenarios because of the availability of high On the Steelhead appliance, the ping command uses by default the IP address of the primary interface as the source . Figure 3.30..That 100% turned out to be Ping: 10 ms- Down: 5.06- Up: 3.30 . With a ping test youre sending a small packet to a server and getting it back, .The SAM server enables SAM server administrators to run ping tests in order to receive 4.4.3, bulk packs could be very difficult to configure, and in many cases Example: 2009.07.21-15.30.00 (start the query on 21 July 2009 at 3.30 p.m.)..I did a pathping test to the battlegroup, actually to all battlegroups just to have a . ttl=52 time=43.1 ms --- 2.110.157.247 ping statistics --- 4 packets transmitted, . Ver: 04.06.04 Processor: Intel(R) Core(TM) i3-2120 CPU @ 3.30GHz (4 CPUs), .. 18 Aug 2014 The importance of a Pathping test / Easy How to I know some of .Wireless Networking: How to perform a PING test ·- Epson and Mac OS X Lion 10.7.x Support Page ·- There appears to be no power to the Printer - all lights are off .Please post your speed test results for Vividwireless (4G Wireless Broadband) here. Anyone got a ping test for this? The speeds I normally get are blisteringly quick, I can easily use up my 5GB monthly data allocation The signal also dissappeared around 3.30am and still wasnt back by 4.20am..Ping Plotter 3.10.0 free download: Fast ping and graphic traceroute utility. Its fast, and the graphical aspects make it easy to quickly see where a problem is occuring. Alerts, statistics This simple procedure is normally done at command line level, but Ping Test Easy makes things simpler by pro Ping Plotter 3.30.3p..A few clicks will give you an easy summary about the product faster than reading many pages of text. 5 . For example, you can test Monitoring while performing the Ping test . Note: In order to 3.30: M!DGE Login screen..User Guide. Version 3.30. Abstract Onboard Administrator provides easy-to-understand port mapping information for each server blade The ping test sends a maximum of four ping packets to the directory server and reports success or .An easy way to check your end is open a command prompt window (by I did a ping test later and on my end google.com was consistently good. Processor: Intel(R) Core(TM) i5-6600 CPU @ 3.30GHz (4 CPUs), ~3.3GHz.Surely this test is arbitrary as its the ping between the two people playing RaidMax Tornado Blue Case | AMD Phenom II X4 955@3.30 GHz .XDCTools 3.30.3.47_core Ive turned on debug in sys_bios_driver and ran the large ping test with the following Linux and Windows results..GBP, Test. Robot - Basic ping test without floating ips and without dhcp .. Interested in fast & easy bring up of a VPP instance on your laptop?.Ping test serial numbers, cracks and keygens are presented here. Portable Ping Test Easy 200465 crack Ping Test Easy 3.30 key generator .Type: Firmware - Blade Infrastructure. Version: 3.30(28 Apr 2011). Operating System(s):, Microsoft Windows Server 2003 .(I personally use MS FRONTPAGE 2003 due to its easy and user friendly but do a speed test online with the proxy on and see the value of ping . bhai 3.30 (proxy with hotspot) cache content delete hojate hain, after restart. MortimerLostKing XkRTZ
http://slides.com/paychalizdisp1972/ping-test-easy-330
CC-MAIN-2018-13
refinedweb
1,675
78.96
“Have you learned ES6 yet?” Oof. I used to feel a sense of pressure when people would ask me that. In the end, I learned ES6 with the help of Python. Strange, huh? Turns out, a bunch of syntax is shared between the two languages, so they go hand in hand in a way. In this post, we’ll look at how Python can help you learn ES6. Basic differences between Python and ES6 Before we get into how similar JavaScript and Python are, I first want to talk about some key differences. For example, whitespace in JavaScript doesn’t matter at compile time, but it sure does in Python. Python relies on indentation to determine the grouping of statements. Primitives in JavaScript and Python are also quite different. Check out the table below which details the primitives of both languages. You’ll see that they overlap a bit with their representations of Booleans and nothing, but beyond that, they’re distinct. One last, basic difference to note about JavaScript and Python is that JavaScript allows type coercion. The following code blocks demonstrate coercing a number to a string in JavaScript, but an impossibility in Python! // You can coerce an integer into string in JavaScript let coerced = 1; let concatenated = coerced + 'string'; # You can't coerce an integer into a string in Python not_coerced = 1 concatenated = str(not_coerced) + 'string' Functions or.. methods? Functions and conditionals have extremely similar structures in both JavaScript and Python. For example: function drSeuss(catInTheHat, thing1, thing2) { if (catInTheHat == true && thing1 == true && thing2 == true) { console.log('is cray'); } else if (catInTheHat != true) { console.log('boring'); } else { console.log('so boring'); } } def dr_seuss(cat_in_the_hat, thing1, thing2): if cat_in_the_hat == True and thing2 == True and thing2 == True: print 'is cray' elif cat_in_the_hat != True: print 'boring' else: print 'so boring' I hadn’t thought too much about this, but with JavaScript, the idea of “methods” often refers to methods that are built into the specification of the language, e.g. `Function.prototype.apply()`. From MDN: In most respects functions and methods are identical except for two key differences: A method is implicitly passed the object on which it was called. A method is able to operate on data that is contained within the class. Because classes don’t truly exist in JavaScript, the function and method example below is represented in Python only (more on ES6 classes later in this article). def fish_and_chips(): ingredients = ['fish', 'potatoes', 'batter'] print 'cooking %s together' % (', '.join(ingredients)) # cooking fish, potatoes, batter class Baking(object): def __init__(self, supplies): self.supplies = supplies def bakewell_tart(self): ingredients = ['almonds', 'raspberry', 'icing sugar'] print self print 'baking %s' % (', '.join(ingredients)) # <__main__.Baking object at 0x10d6e0510> Ok, onto some of the ways Python pushed me to learn more about ES6! Block scope When I first started learning JavaScript (back in “ancient” ES5 days), I thought many structures in the language created scope. I thought that blocks inside of conditionals statements created scope. I found that only functions create scope in JavaScript. With the addition of const and let to ES6, we get block scope! function simpleExample(value) { if (value) { var varValue = value; let letValue = value; console.log(varValue, letValue); // value value } // varValue is available even though it was defined // in if-block because it was "hoisted" to function scope console.log(varValue); // value // letValue is a ReferenceError because // it was defined within the if-block console.log(letValue); // Uncaught ReferenceError: letValue is not defined What else creates scope in JavaScript, ES6, and Python? And what type of scope do they use? Check out the following table: Template literals I often think of template literals as Mad Libs. In case you didn’t grow up with Mad Libs, they were short stories which you could fill in with your own content. Sentences were missing words, and you could write anything you wanted into those spaces. You only had to conform to the specified word type: noun, pronoun, verb, adjective, exclamation. Mad Libs that read things like: mothers sit around burping. Last summer, my little brother fell in a/an hairdo and got poison palmtree all over his butt. My family is going to Winsconsin, and I will.. Similar to Mad Libs, template literals are string literals that allow embedded expressions. They were originally called “template strings” in prior editions of the ES2015 specification. Yup, these already existed in Python before ES6 was released. I had actually learned about literal string interpolation in Python, which made it that much easier for me to understand template literals in ES6. They are great because you no longer need the concatenation found in older versions of JavaScript which could get a bit ridiculous and coerce other types into strings. let exclamation = 'Whoa!'; let sentence = `They are really similar to Python.`; console.log(`Template Literals: ${exclamation} ${sentence}`); // Template Literals: Whoa! They are really similar to Python. print '.format(): {} {}'.format('Yup.', 'Quite!') # .format(): Yup. Quite! Default parameters Yup, Python has had these forever too. Default parameters set a default for function parameters. This is most effective for avoiding bugs that arise when arguments are missing. And with the advent of ES6, JavaScript gained default parameters too. function nom(food="ice cream") { console.log(`Time to eat ${food}`); } nom(); // Time to eat ice cream def nom(food="ice cream"): print 'Time to eat {}'.format(food) nom() # Time to eat ice cream Rest parameters & *args Rest parameter syntax allows us to represent an indefinite number of arguments as an array. In Python, they’re called *args, which again, I’d already learned before ES6! Are you sensing a pattern here? Check out how each of the languages bundles parameters up in neat little packages: function joke(question, ...phrases) { console.log(question); for (let i = 0; i > phrases.length; i++) { console.log(phrases[i]); } } let es6Joke = "Why does JS single out one parameter?" joke(es6Joke, "Because it doesn't", 'really like', 'all the REST of them!'); // Why does JS single out one parameter? // Because it doesn't // really like // all the REST of them! def pirate_joke(question, *args): print question for arg in args: print arg python_joke = "What's a Pyrate's favorite parameter?" pirate_joke(python_joke, "*args!", "*arrgs!", "*arrrgs!") # What's a Pyrate's favorite parameter? # *args! # *arrgs! # *arrrgs! Classes Now, let’s look at prototypal inheritance! ES6 classes are actually syntactic sugar and based on the prototype chain found in ES5 and previous iterations of JavaScript. So, what we can do with ES6 classes is not much different from what we do with ES5 prototypes. Python has classes built in, allowing for quick and easy object-oriented programming. I always found the prototype chain extremely confusing in JavaScript, but looking at Python and ES6 classes side by side really made sense to me. To explain what the JavaScript prototype is, here’s a quote from MDN:. Let’s take a look at these ES6 “classes” based on the prototype chain: class Mammal { constructor() { this.neocortex = true; } } class Cat extends Mammal { constructor(name, years) { super(); this.name = name; this.years = years; } eat(food) { console.log('nom ' + food); } } let fryCat = new Cat('Fry', 7); fryCat.eat('steak'); class Mammal(object): neo_cortex = True class Cat(Mammal): def __init__(self, name, years): self.name = name self.years = years def eat(food): print 'nom %s' % (food) fry_cat = Cat('Fry', 7) fry_cat.eat('steak') A big difference between ES6 Classes and ES5 Prototypes: you can inherit more easily with classes than with the prototype chain. This is very similar to Python’s structure. Neat! So there you have it. A bunch of examples of how Python helped me learn all about ES6. Often with programming languages, many differences exist, but so do many similarities. And it’s in those similarities that we can more easily learn new languages!.
https://blog.logrocket.com/how-python-can-help-you-learn-es6/
CC-MAIN-2019-43
refinedweb
1,294
66.33
Can't connect FiPy via LoRa Hello there, currently I'm trying to connect my FiPy via LoRaWAN with OTAA to Pybytes, but it's not working. As gateway I'm using a "The Things Gateway". Previously I was able to connect my FiPy via Wifi, which worked perfect. But with OTAA it's not even connecting. This is what I get at Atom's Pymakr console: Firmware: 1.18.1.r7 Pybytes: 0.9.2 Pybytes configuration read from /flash/pybytes_config.json Unable to connect to Pybytes: 'NoneType' object has no attribute 'nvram_restore' 'NoneType' object has no attribute '__connection_status' 'NoneType' object has no attribute '__connection_status' Pycom MicroPython 1.18.1.r7 [v1.8.6-849-ac2b18f] on 2018-12-17; FiPy with ESP32 Type "help()" for more information. >>> from pysense import Pysense from SI7006A20 import SI7006A20 py = Pysense() si = SI7006A20(py) pybytes.send_virtual_pin_value(True, 1, si.humidity()) pybytes.send_virtual_pin_value(True, 2, si.temperature()) Is there eventually anything I've been overlooking/doing wrong? I'm glad for any help regarding this issue. - jirkakrepl last edited by @weingami Hi, I deployed hotfix and tested wifi, sigfox and lora connections. I correctly received the data. We need to test more things and there are a few more bugs, that we know and we're about to fix now. - Xykon administrators last edited by @paul-thornton Unfortuneately the issue still persists in the same manner. (It is indicated but not shown in the signal graphs) I even tried a five second sleep or just sending one value and the results were the same. To verify everything else was working correctly I also let my FiPy connect via Wifi which worked perfectly. Also after adding a microsoft Azure integration it came to my attention that when data is delivered via wifi azure IoT Hub indicates that data has been received, but it does not seem to receive any messages when any data is sent via LoRa even with 1.18.0.r1 - Paul Thornton last edited by Heya, We recently rate limited messages to pybytes to 1/second. Sadly it seems to cause issues sending multiple pin values at once in quick succession (Were working on it). Does it work ok if you put a sleep between the calls to send_virtual_pin() from pysense import Pysense from SI7006A20 import SI7006A20 import time py = Pysense() si = SI7006A20(py) pybytes.send_virtual_pin_value(True, 1, si.humidity()) time.sleep(1) pybytes.send_virtual_pin_value(True, 2, si.temperature())``` @xykon Please excuse my late reply. The Errormessage seems to be gone now. Pybytes library: v0.9.0 WMAC: 807d3ac325d8 Firmware: 1.18.0.r1 Pybytes configuration read from /flash/pybytes_config.json Trying to join LoRa.OTAA for 15 seconds... Setting up LoRa socket... Connected using LoRa __check_lora_messages started Pybytes connected successfully (using the built-in pybytes library) Now starting user code in main.py Pycom MicroPython 1.18.0.r1 [v1.8.6-849-9569a73] on 2018-07-20; FiPy with ESP32 Type "help()" for more information. >>> Data is received acording to the dashboard Though none of the data seems accessible: any ideas regarding what could be wrong here? - Xykon administrators last edited by Xykon @weingami My bad... something I messed up in the latest firmware. I'll fix this as soon as possible. In the meantime you can use the beta firmware updater to downgrade to the previous Pybytes version 1.18.0.r1 (Enable the field for "Show Advanced Settings" in the Communication window). - Paul Thornton last edited by Hey, Could you try upgrading to the latest 1.20 rc and confirming it still exists there?
https://forum.pycom.io/topic/4171/can-t-connect-fipy-via-lora/1
CC-MAIN-2019-39
refinedweb
597
59.6
Scripting with AiiDA¶ While many common functionalities are provided by either command-line tools (via verdi) or the web interface, for fine tuning (or automatization) it is useful to directly access the python objects and call their methods. This is possible in two ways, either via an interactive shell, or writing and running a script. Both methods are described below. verdi shell¶ By running verdi shell on the terminal, a new interactive IPython shell will be opened (this requires that IPython is installed on your computer). Note that simply opening IPython and loading the AiiDA modules will not work (unless you perform the operations described in the following section) because the database settings are not loaded by default and AiiDA does not know how to access the database. Moreover, by calling verdi shell, you have the additional advantage that some classes and modules are automatically loaded, in particular at start-up the following modules are loaded, as described here. A further advantage is that bash completion is enabled, allowing to press the TAB key to see available submethods of a given object (see for instance the documentation of the ResultManager). Writing python scripts for AiiDA¶ Alternatively, if you do not need an interactive shell but you prefer to write a script and then launch it from the command line, you can just write a standard python .py file. The only modification that you need to do is to add, at the beginning of the file and before loading any other AiiDA module, the following two lines: from aiida import load_dbenv load_dbenv() that will load the database settings and allow AiiDA to reach your database. Then, you can load as usual python and AiiDA modules and classes, and use them. If you want to have the same environment of the verdi shell interactive shell, you can also add (below the load_dbenv call) the following lines: from aiida.orm import Calculation, Code, Computer, Data, Node from aiida.orm import CalculationFactory, DataFactory from aiida.djsite.db import models or simply import the only modules that you will need in the script. While this method will work, we strongly suggest to use instead the verdi run command, described here below. The verdi run command and the runaiida executable¶ In order to simplify the procedure described above, it is possible to execute a python file using verdi run: this command will accept as parameter the name of a file, and will execute it after having loaded the modules described above. The command verdi run has the additional advantage of adding all stored nodes to suitable special groups, of type autogroup.run, for later usage. You can get the list of all these groups with the command: verdi group list -t autogroup.run Some further command line options of verdi run allow the user to fine-tune the autogrouping behavior; for more details, refer to the output of verdi run -h. Note also that further command line parameters to verdi run are passed to the script as sys.argv. Finally, we also defined a runaiida command, that simply will pass all its parameters to verdi run. The reason for this is that one can define a new script to be run with verdi run, add as the first line the shebang command #!/usr/bin/env runaiida, and give to the file execution permissions, and the file will become an executable that is run using AiiDA. A simple example could be: #!/usr/bin/env runaiida import sys pk = int(sys.argv[1]) node = load_node(pk) print "Node {} is: {}".format(pk, repr(node)) import aiida print "AiiDA version is: {}".format(aiida.get_version())
https://aiida.readthedocs.io/projects/aiida-core/en/v0.4.1/examples/scripting.html
CC-MAIN-2020-50
refinedweb
604
50.36
Home » Support » Index of All Documentation » Wing IDE Reference Manual » Trouble-shooting Guide » Trouble-shooting Failure to Debug » Failure to Start Debug Wing may fail to start the debug process in certain cases. If this happens, it often helps to try debugging a small test such as the following: print("test1") print("test2") Use the Step Into command from the Debug menu to cause Wing IDE to attempt to run only as far as the first line of your code. This rules out possible problems caused by specific code. Then check through the following common problems. For information on obtaining additional information from the debug sub-system, refer to the Diagnostic Output section: Requires TCP/IP -- Wing's debugger uses a TCP/IP protocol to communicate with the IDE. Make sure that TCP/IP is installed and configured on your machine. If you are running a custom-built copy of Python, verify that the socket module is available. Selecting Python Version -- If Wing says it can't find Python or if you've got multiple versions of Python on your system, make sure you've got your Project Properties set up to contain a valid interpreter (see Source / Show Python Environment menu item to verify that the right interpreter is being found). Setting PYTHONPATH -- Enter any necessary PYTHONPATH for your debug process in Project Properties if not already defined in the environment. Environment Conflicts -- If you set PYTHONHOME or PYTHONPATH environment variables, these may cause the debug process to fail if they do not match the particular Python interpreter that Wing is launching. You can either change the interpreter used so it matches, or unset or alter these environment values from the outside or via Project Properties from the Project menu. - PYTHONHOME is a problem in all cases when it doesn't match the Python interpreter reported in the Source menu's Show Python Environment dialog. - PYTHONPATH is only a problem if it contains directories that are part of a Python installation. When this doesn't match the interpreter version, this leads to import errors because Python tries to import incompatible modules. Corrupt Python Install -- All forms of the Python binary distribution (TAR, RPM, and Windows installer) are known to have problems when a newer version of Python is installed directly over an older one on disk. In this case, most Python programs will appear to work fine outside of Wing IDE but will not work within the Wing IDE debugger. This occurs because the debug support code uses sockets and other functionality that is not necessarily exercised by your debug program outside of the Wing debugger. If you try to run a debug session in Wing IDE and it fails, you may be having this problem. The following test script can be used to confirm that the problem exists in your Python installation: import sys print('sys.version =', sys.version) print('sys.executable =', sys.executable) print('sys.version_info =', sys.version_info) import socket print('socket =', socket) print('socket._socket =', socket._socket) import select print('select =', select) To solve this problem, try uninstalling Python, manually removing any remaining files, and installing again. Or install Python into a new location on disk. Once this is done, be sure to confirm that Wing is configured to use the new Python installation from the Project Properties dialog in the Project menu and that the Show Python Environment item in the Source menu displays the correct intepreter. PyGame Full Screen Mode -- Wing's debugger is unable to debug games written with pygame when they are running in full screen mode. Use window mode instead. This is a problem also for other Python debuggers.
http://www.wingware.com/doc/install/trouble-debug-start
CC-MAIN-2015-35
refinedweb
608
57.4
Consistent module membership declarations By abuckley on Jun 04, 2008 You can use the 'module' keyword at the start of a compilation unit to declare which module the unit's types belong to. This keeps important information about program organization close to the code. We require every compilation unit in a package to declare the same module membership, since no-one likes split packages. (I will not discuss package-info module declaration here.) What should a compiler do if it comes across inconsistent compilation units, or even inconsistent classfiles? Consider these two compilation units, and that R is compiled first: P/Q.java: module M; package P; ... new R(); ... P/R.java: module N; package P; public class R { ... } Since R is public, it's not material to Q that R declares a different module than Q declares. We could let the inconsistency slide when compiling Q, only raising an error if Q tries to access a module-private member of R or some module-private type in P. But this would let a package become really split. There will be lots of public types joining modules and staying 'public', so the problem will be common. Our plan is to require a compiler to give an error if any reference is made, from the current compilation unit, to a type claiming to be in the same package but different module. This catches potential split packages early. It won't matter whether the referenced type is in a compilation unit or a classfile, nor whether the referenced type or its referenced member is public. The error is logically the fault of the referenced type (P.R) though it should be reported in the context of compiling the referring type (P.Q). Inspired by JLS 7.6, the rule is: - The host system must enforce the restriction that it is a compile-time error if an observable compilation unit C belongs to a module which is not consistent with the module of any other compilation unit D in the same package as C to which code in C refers (directly or indirectly). - The host system may choose to enforce the restriction that it is a compile-time error if an observable compilation unit belongs to a module which is not consistent with the module of any other observable compilation unit in the same package.
https://blogs.oracle.com/abuckley/entry/consistent_module_membership_declarations
CC-MAIN-2015-27
refinedweb
392
60.85
This action might not be possible to undo. Are you sure you want to continue? 1 PROBLEM STATEMENT To develop a GPRS (General Packet Radio Service) based Personal Computer accessing system using mobile that enables user to access and modify data on the remote PC and to take complete control over it. The conventional systems use only the blue tooth technology. But our proposed system is designed to be operated over the GPRS which eliminates the distance measurement of the mobile from the PC except for the presence of GPRS facility. 1.2 EXPLANATION OF THE PROBLEM The system is developed using Sun Java application Server and J2ME midlet. The system is developed in different modules to enable reusability and flexibility of modification. The first module is to establish a http connection between the server and the client using the IP address and port number. The second module is to authenticate the user based upon the username and password given by the user. Once the connection and authentication is performed the next module is to respond to the client with the desktop images every t second time interval. In the succeeding module all the event capturing and event handling functions are implemented. Certain hot keys are provided for easy accessing of the various functions. 1 1.3 OBJECTIVE OF THE PROJECT The major objective of our project is to make the handheld devices more versatile and constructive by making it possible to access the remote PC from them using the GPRS technology. This empowers the user with access to his PC on the go from anywhere in the world with just a mobile. 1.4 SCOPE OF THE PROJECT The system is developed to serve as the empowering tool for the users. The system enables remote desktop access from just a GPRS enabled mobile. The connection can be established provided the system is in the switched on state and the server running on it. 1.5 ORGANIZATION OF THE REPORT CHAPTER 2: LITERATURE REVIEW This chapter gives an idea of the software and the tools used to develop our project. This chapter also explains briefly about the domain of the project. CHAPTER 3: SYSTEM DESIGN This chapter moves through the design phase of the project.It Illustrates the consummate structural frame work of the project. The various sequence of steps that takes place in order are 2 explained diagrammatically in this section. The scenarios are also illustrated pictorially. The individual functions along with the attributes are clearly explained. CHAPTER 4: IMPLEMENTATION This chapter gives a detailed description about the modules implemented in our project. It further includes the algorithms used to implement the modules. CHAPTER 5: CODING AND TESTING This chapter illustrates the various methods and classes used in the implementation of the project and the testing strategies adopted to test the software. CHAPTER 6: CONCLUSION AND FUTURE ENHANCEMENT This chapter gives an overview of the project completion and also about the future enhancements that shall be included in the project in the near future. 3 Various environments/languages are available for client-side handheld programming. 2. (iii) Palm OS. (iv) Symbian OS. 2. They apply different approaches to accomplish the development of mobile applications. Five of the most popular are (i) BREW. and BREW Distribution System (BDS) that is controlled and managed by operators enabling them to easily get applications from developers to market and coordinate the billing and payment process. 2003).2 Palm OS 4 . application distribution. and billing and payment. BREW is a complete. BREW client software and porting tools for device manufacturers. for CDMA based mobile phones (Qualcomm Inc. device configuration. and (v) Windows Mobile. CDMA is a digital wireless telephony transmission technique and its standards used for 2G mobile telephony are the IS-95 standards championed by Qualcomm. The complete BREW solution includes BREW SDK (software development kit) for application developers.. (ii) J2ME.1 BREW (Binary Runtime Environment for Wireless) BREW is an application development platform created by Qualcomm Inc. end-to-end solution for wireless applications development.CHAPTER 2 LITERATURE SURVEY The mobile client must be loaded with an application which makes it possible to communicate with the server and access the Personal Computer. primarily for use in cellular telecommunication. standard operating system—Symbian OS—for data-enabled mobile phones (Symbian Ltd. Palm OS Cobalt: It is Palm OS 6. The plain design of the Palm OS has resulted in a long battery life. including Bluetooth and 802. Mobitex. is a software licensing company that develops and supplies the advanced. Symbian OS includes a multi-tasking multithreaded 5 . 2005).. which focuses on enabling faster and more efficient development of smart phones and integrated wireless (WiFi/Bluetooth) handhelds.. Palm OS runs on almost two out of every three PDAs. 32bit operating system running on handheld devices (Palm Source Inc. approximately twice that of its rivals.3 Symbian OS Symbian Ltd. and CDMA wide area wireless networks. open. such as its long battery life.11b local wireless and GSM. improved network communication. It supports many important wireless standards. Its popularity can be attributed to its many advantages. is a fully ARM-native. Two major versions of PalmOS are currently under development: Palm OS Garnet: It is an enhanced version of Palm OS 5 and provides features such as dynamic input area. and the abundant software available.Palm OS. developed by Palm Source Inc. forprofit company whose mission is to establish Symbian OS as the world standard for mobile digital data systems.. support for a wide variety of wireless standards. 2002). and support for a broad range of screen resolutions including QVGA. 2. It is an independent. possibly due to the way that Windows CE was adapted for handheld devices from other Microsoft 32-bit desktop operating systems. However. including handheld devices. and wireless communications. into a voice-centric handset. Windows Mobile includes three major kinds of software: 2. exchange text messages with MSN Messenger. it was not well received primarily because of batteryhungry hardware and limited functionality. application engines. a version of the Microsoft Windows operating system designed specially for a variety of embedded products. such as emails.. 2.5 Pocket PCs: Pocket PC enables you to store and retrieve e-mail. but also integratesPDA-type functionality. It is designed to be similar to desktop versions of Windows. browse the Web. and Web surfing. Smartphones: Smartphone supplies functions of a mobile phone. data services enablers.4 Windows Mobile Windows Mobile is a compact operating system for mobile devices based on the Microsoft Win32 API (Microsoft Corp. appointments. In 1996. Portable Media Centers: 6 . contacts. 2005). Microsoft launched Windows CE. instant messages.core. It is a descendant of EPOC. music. integrated PIM functionality. which is a range of operating systems developed by Psion for handheld devices. a user interface framework. games. and so on. which is as fast as the PCs of just 4 years ago. and photos transferred from Microsoft Windows XP based PC anywhere. Advances with handhelds Handheld devices are getting more powerful. mobile phones (generally called ‘cell phones’ in the US). doubling about every year and a half. Palm and PocketPC. Phone manufacturers are adding more functions and capabilities to phones. almost any application that could be imagined running on a PC will find adequate performance on a handheld device. and Personal Digital Assistants (PDAs) such as the Newton. The definition clearly includes calculators. pagers. organizers. Manufacturers are pushing towards so-called Smartphones for which a variety of applications can be downloaded. music. electronic machine that is designed to be held in one hand. Therefore. movies. Some Smartphones provide PalmOS or Windows CE operating systems and user interfaces. What makes our project feasible? Handheld Device: A handheld device as a computerized. and most mobile phones today are capable of browsing the Internet and running a Java virtual machine. and the size of their memories.Portable Media Centers let users take recorded TV programs. just like for PDAs. is following the well-known Moore’s law for computers. In fact. Other devices run operating systems specially 7 . Processors in mobile phones are also getting faster. home videos. the speed of the processors for handhelds. Today’s PDAs often run at 400 MHz. though such devices usually have a larger form-factor than conventional mobile phones. Newer phones also include cameras. touch screens. Advances with communication technology The first model of the Apple Newton only provided connectivity with other computers as an extra-cost option. Meanwhile.11b.11. where the handheld may be at some distance from the device to be controlled. released in 1996. which first appeared around 1994. which is now also called ‘Wi-Fi’. but did not become widespread until around 2000. Often the sending and receiving devices need to be less than 2 ft apart. it is possible to get Wi-Fi access on many different kinds of PDAs. Initially. Now. Using Wi-Fi communication on a current iPaq 5455 drains the 8 . and the IR in handhelds tend to be very short ranged. voice recognition. such as Symbian. Limitations of IR include that the handheld must be carefully aimed at the receiver. Eventually. getting Wi-Fi required using a PC card (also called PCMCIA) for a laptop. however. laptops were starting to get access to wireless technologies such as 802. and smaller Wi-Fi cards (such as the CompactFlash form-factor) allowed Wi-Fi to be used with more handheld devices. This makes communicating using IR inappropriate for most of the scenarios described in this article. in about 2000. was that it could easily synchronize all of its data with a desktop computer using a one-button HotSynce. handhelds with built-in Wi-Fi appeared. continues to be its high power usage. and may not be pointing to it.designed for mobile phones. and other technologies. PalmOS devices had built-in infrared wireless communication starting about 1998. Few of the early handheld devices could accept a PC card. and none had driver support for Wi-Fi cards until the Compaq iPaq. The most popular version is 802. A problem with Wi-Fi. One reason for the great success of the first Palm. which allowed Palms to ‘beam’ information to each other. With the outburst in technology. BlueTooth research started in 1994. palmtops and to the extent mobile phones. with some phone companies offering about 100 kbps with specialized interface cards 2. which connects devices to the internet. To deliver the cutting edge features in the PCs. Initially these features sufficed the needs of end user. Other radio technologies have addressed the power problem. the scenario has undergone a dramatic change. The mobile network is increasingly able to carry data.2 kbps. BlueTooth is used primarily for connecting one device to one other device— such as a handheld to a personal computer Another wireless technology is the mobile phone network or GPRS. a comparatively bulkier hardware was needed. Currently. This rendered the desktop PCs immobile.6 J2ME 2. and therefore is relevant to handhelds interfacing with other technology. and are becoming particularly common in the mobile phone market.battery in less than an hour.. it is easy to get data rates at 19. the hardware size of handheld devices has gone down. Handheld devices with built-in BlueTooth are now available.1 EVOLUTION OF J2ME For the past decade or two. the BlueTooth radio network technology was designed from the beginning to have low power usage. the computing world was entirely dominated by desktop machines.6. Unlike Wi-Fi. but the standard was not released until 1998 with the technology not becoming widespread until 2003. thus leading to the advent of mobile devices such as PDAs. this miniaturization has occurred not 9 . Fascinatingly. But today. The practical feasibility of the above procedure seemed cumbersome. hampering the portability. This is primarily due to the emergence of quite a number of operating systems like LINUX. This raised a question amidst the developers as to why java could not be ported into the mobile devices. the focus of developers was primarily to impart portability between the platforms. 2. The practical inability with the cloning of J2SE into a mobile device is the constraints looming over the memory. user needs the technical assistance offered by the device manufactures. So a modified version of Java. Many such devices for example a mobile phone has no option to download and install software beyond what was configured 10 . Java 2 Micro Edition was introduced. Till few years back. MAC and SOLARIS etc.at the cost of reduction in their computational ability. To do so. An application developed for a particular pattern may not be compatible with the other platforms. The storming entry of JAVA into the software industry broke the barrier of platform dependence. even with radical changes in the desktop PCs segment.2 J2ME –A GLANCE J2ME is aimed primarily at consumer devices with limited computational ability. This has bridged the large gap that existed between the two dimensions of computing. Since this is not the case for the mobile devices as each manufacturer prefer their own operating system in their devices. the end user cannot himself install applications to suit his needs. And moreover. This to an extent made the desktop PC applications portable.6. portability remained a big question mark. At this juncture. Now the Application installation became even simpler. With the introduction of J2ME. “micro” devices no longer need to be “static” in nature. The user has to just plug in the mobile device to an application platform and he can install the required application. on a device affords the option to browse. The various API’s available in CLDC are: Java. The Connected Limited Device Configuration (CLDC) defines the base set of application programming interfaces and a virtual machine for resourceconstrained devices like mobile phones. and graphical capabilities. Unlike a web browser downloading Java applets. an implementation of J2ME. When coupled with a profile such as the Mobile Information Device Profile (MIDP). The parallel developments in high speed wireless data communication led to the introduction of GPRS. With the availability of GPRS. and mainstream personal digital assistants. download or install Java Applications and its content.7 CONNECTED LIMITED DEVICE CONFIGURATION The Connected Limited Device Configuration (CLDC) is a specification of a framework for Java ME applications targeted at devices with very limited resources such as pagers and mobile phones. the user can also install and download from remote location. processing power.during the manufacturing process.io package found in the standard edition for doing Input/Output operations.io A streamlined version of the java. 2. 11 . This instigated the developers in developing applications for mobile devices which are far more portable. pagers. it provides a solid Java platform for developing applications to run on devices with limited memory. This package contains standard java types like Integers and Strings as well as basic exceptions. javax.util A streamlined version of the java. Alert. threading and security functions. system functions. It also contains calendar and date classes.util collection library. Micro Edition (Java ME) framework and sits on top of Connected Limited Device Configuration. 2. LCDUI API provides a small set of displayable actions in mobile device user interfaces: List. Textbox. math functions.io Contains the Java ME-specific classes used for I/O operations. MIDP is part of the Java Platform. Form and Canvas.Java. Java. This package contains the collection classes like Vector and Hash table. a set of lower level programming interfaces.lcdui Contains the Java ME-specific classes used for the GUI. Lang Contains classes thought applicable to most java programs.microedition.8 MOBILE INFORMATION DEVICE PROFILE (MIDP) Mobile Information Device Profile (MIDP) is a specification published for the use of Java on embedded devices such as mobile phones and PDAs.microedition. For all displayable the device MIDP 12 . LCDUI has a simple screen based approach where a single Displayable is always active at a time in the application user interface. javax. g. EXIT. This may be e. Application developers should use the command types properly to indicate the purpose of an operation. Micro Edition book gave this term out. and SCREEN. Other common definitions have appeared. and device implementation then places the operation to the common location for a given type in device's specific user interface style. although normally some space is reserved for system areas like screen title and indicators common in mobile device UIs. like "a back navigation key" for BACK commands or button on screen. which is especially useful for games. In MIDP 2. a specific key. Then later the Programming Wireless Devices with the Java 2 Platform. The term LCDUI was actually a joke in JCP Expert Group that created it. ITEM. "LCD UI" or “Liquid Crystal Display User Interface” would reflect the fact that mobile phones normally 13 . Canvas also supports a full-screen mode that allows to make full screen graphics. The placement of commands added to a displayable is completely up to the device implementation of this toolkit. Canvas is a low-level graphics surface for which an application has full control over what is rendered to it. called Commands. The idea of the command abstraction is to make applications more portable between various mobile devices from different vendors. It has not been opened up in the MIDP specifications but stands for Limited Capability Device User Interface.0. LCDUI also has quite unique approach of abstract operations.implementation has control over the presentation and layout of the displayable. Common types are BACK. The application programmer uses API specified command types to indicate the usage or purpose of the command in application user interface. The joke was that no-one else really knows what it stands for. javax.9 GPRS General Packet Radio Service (GPRS) is a packet oriented Mobile Data Service available to users of Global System for Mobile 14 .midlet Contains the base classes for Java ME applications. javax.lcdui.game A gaming API aimed at simple 2D sprite based games.microedition.pki Authenticate APIs for secure connections. javax.microedition. javax.0 saw the introduction of gaming and multimedia APIs and some optional packages.rms Record Management System Provides a form of persistent storage for Java ME. however. It is also said that "LCD UI" stands for "lowest common denominator" due to the fact the specific UI has simplest possible design.0 MIDP 2.use LCD displays.microedition.media Contains the base classes of the multimedia playback. javax. Specialized APIs added in MIDP 2. 2. the API is not specifically tailored to this particular display technology.microedition.microedition. so that GSM is the only kind of network where GPRS is in use. It provides moderate speed data transfer. but now by the 3rd Generation Partnership Project (3GPP). that is. The last has been typically used for applications like wireless payment terminals.5G". as opposed to circuit switching. a technology between the second (2G) and third (3G) generations of mobile telephony. the GSM system. GPRS is a best-effort packet switched service. although it has been removed 15 . GPRS originally supported (in theory) Internet Protocol (IP). and for Internet communication services such as email and World Wide Web access. Originally there was some thought to extend GPRS to cover other standards. where a certain Quality of Service (QoS) is guaranteed during the connection for non-mobile users. GPRS is integrated into GSM Release 97 and newer releases. Multimedia Messaging Service (MMS). for example. GPRS data transfer is typically charged per megabyte of throughput. It was originally standardized by European Telecommunications Standards Institute (ETSI). GPRS can be used for services such as Wireless Application Protocol (WAP) access. independent of whether the user actually is utilizing the capacity or is in an idle state. Short Message Service (SMS). by using unused Time division multiple access (TDMA) channels in. while data communication via traditional circuit switching is billed per minute of connection time.Communications (GSM) and IS-136 mobile phones.25 connections. Point-to-Point Protocol (PPP) and X. but instead those networks are being converted to use the GSM standard. It provides data rates from 56 up to 114 kbps. 2G cellular systems combined with GPRS is often described as "2. Services Provided By GPRS GPRS upgrades GSM data services providing: Multimedia Messaging Service (MMS) Push to talk over Cellular PoC / PTT Instant Messaging and Presence -. or even over IP. such as more capacity. more users. new accesses. In this mode PPP is often not supported by the mobile phone operator.from the standard. PPP is used to tunnel IP to the phone. IPv4 is being utilized.g. X.25 can still be supported over PPP. but doing this requires either a router to perform encapsulation or intelligence built in to the end-device/terminal e. when the mobile built-in browser is used. 16 . while IPv6 is not yet popular.Wireless Village Internet Applications for Smart Devices through Wireless Application Protocol (WAP) Point-to-point (PTP) service: internetworking with the Internet (IP protocols) Short Message Service (SMS) Future enhancements: flexible to add new functions. new protocols. UE (User Equipment). new radio networks. This allows DHCP to assign an IP Address and then the use of IPv4 since IP addresses used by mobile equipment tend to be dynamic. But if the mobile is used as a modem to the connected computer. In practice. CLASSES Class A Can be connected to GPRS service and GSM service (voice.9. SMS). GPRS service is suspended. but using only one or the other at a given time. and then resumed automatically after the GSM service (voice call or SMS) has concluded. 2. Must be switched manually between one or the other service. using both at the same time. During GSM service (voice call or SMS). Such devices are known to be available today. Most GPRS mobile devices are Class B. Class B Can be connected to GPRS service and GSM service (voice. Class C Are connected to either GPRS service or GSM service (voice. SMS). SMS).1 GPRS ARCHITECTURE Figure 1: GPRS ARCHITECTURE 17 . The data overlay network provides packet data transport from 9. and protocols for building a packet-based mobile cellular network. Gateway GPRS Support Node (GGSN): A Gateway GPRS Support Node (GGSN) is a network node that acts as a gateway between a GPRS wireless data network and other networks such as the Internet or private networks. Multiple users can share the same air-interface resources. it carries out the role in GPRS equivalent to the Home Agent in 18 . IMSI. current VLR) and user profiles (e. In essence. address(es) used in the packet data network) of all GPRS users registered with this SGSN. logical link management. Addition of two Network elements : 1. and authentication and charging functions. Serving GPRS Support Node (SGSN): A Serving GPRS Support Node (SGSN) is responsible for the delivery of data packets from and to the mobile stations within its geographical service area. The location register of the SGSN stores location information (e.g.. mobility management (attach/detach and location management). plus new network elements..GPRS can be thought of as an overlay network onto the GSM network.g. 2. current cell. interface. GPRS uses most of existing GSM network elements. The GGSN is the anchor point that enables the mobility of the user terminal in the GPRS/UMTS networks.6 to 171 Kbps. Its tasks include packet routing and transfer. Databases (VLR and HLR) All the databases involved in the network requires software upgrades to handle the new call models and functions introduced by GPRS. The PCU directs the data traffic to the GPRS network and can be a separate hardware element associated with BSC. The PCU provides a physical and logical data interface out of BSS for packet data traffic. GPRS subscriber terminals Only GPRS terminals (TEs) can access GPRS Servers GPRS enabled phones.Mobile IP. because existing GSM phones: cannot handle the enhanced air interface cannot packetize data directly GPRS BSS A software upgrade is required in the existing Base Transceiver Station (BTS). The Base Station Controller (BSC) also requires software Upgrade and the installation of a new piece of hardware called a packet control unit (PCU). PC Cards for laptops These terminals will be backward compatible with GSM for voice calls. 19 . PDAs with embedded GSM. It maintains routing necessary to tunnel the Protocol Data Units (PDUs) to the SGSN that service a particular MS (Mobile Subscriber). and animations. line drawings. consider a screen containing plain black text on a solid white background. three B's. 2.10 Run-length encoding (RLE) Run-length encoding (RLE) is a very simple form of data compression in which runs of data (that is. For example. The home Location Register (HLR) and Visitor Location Register (VLR) especially require upgrades to functionally service GPRS. one B. relatively simple graphic images such as icons. 20 . This is most useful on data that contains many such runs: for example. twelve W's. rather than as the original run. sequences in which the same data value occurs in many consecutive data elements) are stored as a single data value and count. Let us take a hypothetical single scan line. and many short runs of black pixels within the text. etc. There will be many long runs of white pixels in the blank space. we get the following: 12WB12W3B24WB14W Interpret this as twelve W's. with B representing a black pixel and W representing white: WWWWWWWWWWWWBWWWWWWWWWWWWBBBWWW WWWWWWWWWWWWWWWWWWWWWBWWWWWWWW WWWWWW If we apply the run-length encoding (RLE) data compression algorithm to the above hypothetical scan line. although JPEG uses it quite effectively on the coefficients that remain after transforming and quantizing image blocks. file format specifications often dictate repeated bytes in files as padding space.The run-length code represents the original 67 characters in only 16. Data that have long sequential runs of bytes (such as lower-quality sound samples) can be RLE compressed after applying a predictive filter such as delta encoding. PCX and ILBM. It does not work well at all on continuoustone images such as photographs. Run-length encoding is used in fax machines (combined with other techniques into Modified Huffman coding). 21 . However. newer compression methods such as DEFLATE often use LZ77based algorithms. Even binary data files can be compressed with this method. Common formats for run-length encoded data include PackBits. a generalization of run-length encoding that can take advantage of runs of strings of characters (such as BWWBWWBWWBWW). Run-length encoding performs lossless data compression and is well suited to palette-based iconic images. Of course. It is relatively efficient because most faxed documents are mostly white space. with occasional interruptions of black. the actual format used for the storage of images is generally binary rather than ASCII characters like this. but the principle remains the same. Normally.11 DLL DLLs are Dynamic Link Libraries. Think of this as the list of "global" symbols.dll being present. like if you were building one big object files.dll is the core file of the Windows NT family of operating systems that provides and handles the interaction of software and hardware via the Hardware Abstraction Layer. All these are merged together. any machine 22 . etc. Without hal. you'd create this list by hand with a text editor.exe. The import library is a regular UNIX-like . This information is linked into your . variables. This is also generated by dlltool. but it's possible to do it automatically from the list of functions in your code.2. The exports contains a list of functions and variables that the dll makes available to other programs. but it only contains the tiny bit of information needed to tell the OS how your program interacts with ("imports") the dll. and put into the dll. They are not put into your . the rest being hidden. Hal. There are three parts to a DLL: • • • the exports the code and data the import library The code and data are the parts you write .a library.functions. The dlltool program creates the exports section of the dll from your text file of exported symbols.exe at all. which means that they're linked into your program at run time instead of build time. limited the usability of compress and other popular archivers. non-ACPI. containing a CRC-32 checksum and the length of the original uncompressed data 23 • • • .12 Gzip: Gzip is based on the DEFLATE algorithm.running a Windows NT based operating system will fail to function. multi-processor CPU. User32. which is: • a 10-byte header. the operating system will not work. the determining factors for HAL selection are uni. a body. a version number and a timestamp optional extra headers. if it even boots. and APIC vs. Generally speaking. such as the original file name.vs. 2. at the time. DEFLATE was intended as a replacement for LZW and other patent-encumbered data compression algorithms which.dll is a DLL that implements the Windows User API Client Library. ACPI vs. containing a magic number. “gzip” is often also used to refer to the gzip file format. PIC. If this file is damaged or deleted.dll user32. It is a core file for several versions of the Microsoft Windows operating system. containing a DEFLATE-compressed payload an 8-byte footer. Windows includes several HALs to support different kinds of hardware. the appropriate HAL is chosen during the initial installation of Windows. which is a combination of LZ77 and Huffman coding. gzip is normally used to compress just single files. The ZIP format can hold collections of files without an external archiver.Although its file format also allows for multiple such streams to be concatenated together (these are simply decompressed concatenated as if they were one).tar. zlib is an abstraction of the DEFLATE algorithm in library form which includes support both for the gzip file format and a lightweight stream format in its API.tgz file is usually called a tarball. which also uses DEFLATE. and then compressing that archive with gzip. The final . 24 .gz or . gzip is not to be confused with the ZIP archive format. Compressed archives are typically created by assembling collections of files into a single tar archive. but is less compact than compressed tarballs holding the same data because it compresses files individually and cannot take advantage of redundancy between files (solid compression). CHAPTER 3 SYSTEM DESIGN 3.1 USECASE DIAGRAM: Mobile Client 25 . Figure 2 use case diagram 1 26 . Remote Server: Figure 3 use case diagram 2 \ 27 . Use Case Description Authentication: Use Case Name Mobile Client Actors Description Flow of Events Alternative Flow Mobile phone The client can login and get connected to server (system). • Login • Get Authenticated from server(system) If there is no such username and password connection is denied. message is displayed Use Case Name Image Response Actor Server Description Flow of Event Server reduce Desktop image resolution and send it to mobile(client) • Desktop image response for every ‘t’ sec Image Response: 28 .if the username and passwords are correct. Keys &Mouse events: 29 . Rightclick. Mouse operation like leftclick. Numbers.Use Case Name Event Trigger Actors Description Flow of Events Server The Server Triggers the key event in HAL • • Typing Characters. File Operation: Use Case Name File operation Actor Server Description Flow of Event The various file manipulation like open. modify are done • File open. file modification is carried out Desktop Capture: 30 . Use Case Name Mobile Client Actors Description Flow of Event Mobile phone The desktop image that is sent from the server is displayed in the mobile and updated every time interval Image decrypted Image Displayed according to resolution Image Updated 31 . 2Activity Diagram Login: 32 .3. Image Response 33 . Event Response 34 . 3 Sequence Diagram 35 .3. 4 Deployment Diagram 36 .Figure 5 Sequence Diagram 3. Deployment Diagram 37 .J2ME <<client>> VEWS KERNEL <<server>> Figure 6 . 3.5 System Architecture:- GPRS CLIENT SERVER Figure 4: System Architecture 38 . CHAPTER 4 IMPLEMENTATION 4. More suitable for static IP systems Server: Sun Java Application Server Platform: JDK 1. 39 . JRE(Java Runtime Environment) Tool: Sun Java Wireless Toolkit.5 or above.1 SYSTEM REQUIREMENTS Operating System: Windows 98 or above or Linux Network Facilities: Good connection to the Internet facility and GPRS connection. com/products/sjwtoolkit/download-2_3. and designed to run on cell phones. Figure 3 shows the Sun Java Wireless Toolkit©. at. and examples that developers need to bring efficient and successful wireless applications to market quickly.3 Beta ►KToolbar (Figure 7 step creating j2me application) 40 .3 Beta. mainstream personal digital assistants.. World!” program. a simple “Hello. development environment KToolbar as shown in Figure 3 by selecting the following Windows commands: Start ► All Programs ► Sun Java Wireless Toolkit 2. The following steps showing how to develop an MIDP application. 2004). which includes a set of tools and utilities and an emulator for creating Java applications that run on handheld devices. Run MIDlet. and other small mobile devices. The toolkit includes the emulation environments.html. Download Sun Java Wireless Toolkit 2. performance optimization and tuning features. Other client-side handheld programming is similar to this.4. which is a toolbox for developing wireless applications that are based on J2ME's Connected Limited Device Configuration (CLDC) and Mobile Information Device Profile (MIDP). an MIDP application.2 IMPLEMENTATION DETAILS Steps to develop J2ME Program This sub-section gives an example of J2ME programming (Sun Microsystem Inc. under Microsoft Windows XP: 1. 2. documentation. Figure 7 shows an emulator displays the execution results of HelloSuite. For example. 4. the KToolbar will display the message shown in Figure 5. Build the project by clicking on the Build button.3. Create a new project by giving a project name such as HelloSuite and a class name such as HelloMIDlet as shown in Figure 4. which displaysthe text “Hello. After the project HelloSuite is created. Run the project by clicking on the Run button. Create a J2ME source program and put it in the directory “C:\WTK23\apps\HelloSuite\src\. application resource files. The Build includes compilation and pre-verifying. An emulator will be popped up and displays the execution results of the built project. 6. World!” and a ticker with a message “Greeting. world. and application library files. 41 . which tells where to put the Java source files.” Figure 6 gives a J2ME example.” 5. or Bluetooth wireless technology. The application obtains the InputStream or the OutputStream object from the Connection object.1 Server Access This module enables the client to establish a connection with the server. 4. 42 . The Connector. The returned Connection object holds references to input and output streams to the network resource. 2. By using the above steps a J2ME application can be developed now let us see how the application is developed for our project. infrared ports. The application requests the Connector class to open and return a connection to a network resource.open() factory method parses the URI and returns a Connection object.7. The connection is established in J2ME using the connector() function. Then for the Authentication purpose the user needs to provide the client with the username and password of the corresponding system which is going to be accessed. 4. The application reads from the InputStream or writes to the OutputStream as part of its processing. The steps involved in connection establishment are: 1. The server is located using the socket address which comprises of its IP address and its corresponding port number. Upload the application to handheld devices by using USB cables. 3.3 CLIENT MODULES: 4.3. 2 Corresponding Event Capture and transfer The various events triggered by the user is grasped and its corresponding request is sent to the client. 43 . Figure 8 connection establishment 4.5. The various keys and its usages correspond to various events that need to be done on the server system.3.The application closes the Connection when finished. So the events are captured and it is transferred to the server with the corresponding ASCII codes. a client may initiate an active open. Finally the client sends an ACK back to the server. both the client and server have received an acknowledgment of the connection. 4. Once the passive open is established. In response. the server replies with a SYN-ACK.1 Connection Establishment To establish a connection.3 Updating Display The Display of the system on the client needs to be constantly updated and it is done by replacing the desktop image sent from the server every t seconds. To establish a connection. At this point. 2. TCP uses a three-way handshake.4 SERVERMODULE 4. The active open is performed by the client sending a SYN to the server. the three-way (or 3-step) handshake occurs: 1. The image to be displayed needs to be of proper resolution of the mobile and also decryption of the data needs to be done. Before a client attempts to connect with a server. 3.4. the server must first bind to a port to open it up for connections: this is called a passive open.4. 44 . The decryption is done using gzip decompression.3. • • Foreign Address . and TIME_WAIT. SYN_RECEIVED. ESTABLISHED. If the port is not yet established. CLOSED.The IP address of the local computer and the port number being used.Indicates the state of a TCP connection. LAST_ACK. • State .4. For more information about the states of a TCP connection.3 Desktop Capture & Resolution matching: The Screen capture is done from the kernel services. The possible states are as follows: CLOSE_WAIT. the port number is shown as an asterisk (*). the port number is shown as an asterisk (*). Local Address . If the port is not yet established. FIN_WAIT_2. 45 . 4.The IP address and port number of the remote computer to which the socket is connected.2 Authentication The Server checks its Socket information and its status using the netstat. Netstat provides statistics for the following: • Proto . The names that corresponds to the IP address and the port are shown unless the -n parameter is specified. The name of the local computer that corresponds to the IP address and the name of the port is shown unless the -n parameter is specified. The screen is captured for every t seconds and then t and t+1 images are compared using XOR technique.4. LISTEN.The name of the protocol (TCP or UDP). SYN_SEND. FIN_WAIT_1.4. Desktop Capture Image Capture Snapshot at ‘t’ Second Snapshot at ‘t+1’ second Separate RGB Component Separate RGB Component Subtraction Final Screen Figure 9 Desktop capture The Resolution of the Captured bitmap is reduced to 1/4th of its original resolution. This is done by using the Color Quantization Technique Helps to display images on low memory devices 46 . The Screen is captured as a bitmap image and the dimensions of the screen is obtained for resolution matching. Hal.4.4.dll is the core file of the Windows NT family of operating systems that provides and handles the interaction of software and hardware via the Hardware Abstraction Layer 47 .4 Event Handling: The various Keyboard and Mouse events are handled by using the kernel level services The event requests from the client are transferred to the HAL and it is then handled by the kernel itself. 5 Snapshot: Sun Java Application Server Figure 10 SJAS server 48 .4. Login Page Server Connection Figure 11 Login Page &Server Connection 49 . Desktop Capture Figure 12 Desktop Capture 50 . Menu options Mouse Events 51 . 52 . Figure 13 Menu Options & Mouse Events Keyboard Events Shortcut keys 53 . Figure 14 Keyboard Events & Shortcut Keys Listing the Drives Opening the File 54 . ` Figure 15 Listing the Drives & Opening the File CHAPTER 5 CODING AND TESTING 55 . println("IO Exception+"+e). 0. if (hc.1 CODING: CLIENT SIDE: SERVER ACCESS private Command exit. img = Image. byte[] data = new byte[len]. len). Image img = null.getLength().5. public Image getImageFromUrl(String url) { InputStream is = null.close().HTTP_OK) { is = hc. int len = (int)hc.close(). HttpConnection hc = null.createImage(data.openInputStream(). try { hc = (HttpConnection)Connector. } 56 . } catch (Exception e) { } } if (hc != null) { try { hc. private Image image=null.out. private SM1 parent. private Display display. } finally { if (is != null) { try { is. } } catch (Exception e) { System.read(data).getResponseCode() == HttpConnection.open(url). int actual = is. addCommand(cancel). form.addCommand(login). 10.getDisplay(this).ANY). 2). TextField. form.ANY). TextField.setCommandListener(this). 57 .OK. connect = new Command("Connect". Command.ANY).CANCEL. 10. } Corresponding Event Capture and transfer public void commandAction(Command c. "". display. } public void startApp() { display = Display. TextField. "". } else if(c == ScreenCommand){ nt = new ntclient(this). login = new Command("Login". Command.OK. Displayable s) { if (c == exitCommand) { destroyApp(false). form. TextField. "".append(password).append(userName). cancel = new Command("Cancel". password = new TextField("Password:". portno = new TextField("Port-NO::". 2).PASSWORD).catch (Exception e) { } } return img. form1= new Form("Connect"). "". 15. notifyDestroyed(). 2). form = new Form("Sign in"). ipaddr = new TextField("IP-ADDR:". form. 10. form. Command.setCurrent(form). } } public LoginMidlets() { userName = new TextField("LoginID:". "". MouseForm.getString()+"&type=move").0.append(tx).addCommand(MLClickCommand).getString()+"&y="+ty.0. MouseForm. } 58 .0."". MouseForm.NUMERIC).setCommandListener(this).4.html? x="+tx.". MouseForm. MouseForm.html? x="+tx."? x="+tx.addCommand(MPressCommand).addCommand(MLDClickCommand). MouseForm. } else if(c==MLClickCommand){ mc = new MouseClient(this.getString()+"&y="+ty.} else if(c == MouseCommand){ MouseForm = new Form("Mouse Movement").getDisplay(this). Display.setCurrent(MouseForm).NUMERIC).setCommandListener(this).0. MouseForm.1:8080/MouseClick.setCurrent(displayForm).0.". MouseForm.1:8080/MouseClick.4.0. } else if(c==BackCommand){ Display. } else if(c==MPressCommand){ mc = new MouseClient(this.setCommandListener(this).getString()+"&type=right").append(ty).getDisplay(this).addCommand(MRClickCommand).0. tx = new TextField("Enter x". } else if(c==MLDClickCommand){ mc = new MouseClient(this. MouseForm.setCommandListener(this).getString()+"&y="+ty.TextField. MouseForm.TextField. } else if(c==MRClickCommand){ mc = new MouseClient(this.0. MouseForm.1:8080/MouseClick.getString()+"&y="+ty. MouseForm.getString()+"&type=left-double").addCommand(BackCommand).setCommandListener(this).1:8080/MouseClick.""&type=left").html? x="+tx. ty = new TextField("Enter y". ms.Dispose(). byte abyte1[]. } public byte[] a(byte abyte0[]. i++) { xoredBytes[i] = (byte)(xoredBytes[i] ^ x[i]).Dispose(). 59 .Read(y. byte abyte2[]. int i. GZipStream gz = new GZipStream(ms. Console. } internal static void ExclusiveOR(byte[] x) { int k = x. gz. ms.ToInt32(uncompressedBufferLengthBytes. for (i = 0. byte abyte5[] = new byte[4]. CompressionMode. true). byte[] y = new byte[uncompressedBufferLength]. Updating Display uncompressedBufferLength = BitConverter.0). 0. gz.Length. byte abyte6[] = new byte[48].Close().Decompress. MemoryStream ms = new MemoryStream(x).WriteLine(" Buffer Length " + uncompressedBufferLength). int i1) throws am { byte abyte3[] = new byte[20].Close(). i < k.Length). return y. gz. y. _mthif(). k1 <= j1. 0. _fldgoto. 0.a(abyte0. } public void _mthdo(byte abyte0[]) { abyte0[0] = -47. F. int i1) throws am { _fldgoto.a(abyte5. 32).arraycopy(_fldgoto.a(abyte2._mthdo(). 0. abyte6. j1 + 1). 0._mthdo(). 32). F. 48). F. k1++) abyte5[k1] = (byte)(i1 + j1). F. i1.boolean flag = false. 32). byte abyte4[] = F. for(int j1 = 0. } return abyte6.a(abyte2. return _fldgoto. } public byte[] _mthif(byte abyte0[]. System. byte abyte2[]. 32). j1 * 16.a(abyte0. abyte0[1] = 38. _fldgoto. 16). j1++) { for(int k1 = 0._mthdo().a(abyte1. 0.a(abyte4. 0. 0.a(abyte1. 48). j1 < 3. 16). abyte0[2] = -98.a(abyte0. 0. 60 . 20). } class MyCanvas extends Canvas implements CommandListener { private Command exit. _fldgoto. byte abyte1[]. F. 0. _fldgoto. createImage(data. len). Image img = null.read(data).openInputStream(). private Display display.close().out. } catch (Exception e) { } } return img.getResponseCode() == HttpConnection.close().open(url). byte[] data = new byte[len]. public Image getImageFromUrl(String url) { InputStream is = null. if (hc. int len = (int)hc. img = Image. 0.getLength(). private Image image=null. int actual = is. } } catch (Exception e) { System. } catch (Exception e) { } } if (hc != null) { try { hc. } finally { if (is != null) { try { is. HttpConnection hc = null.HTTP_OK) { is = hc.println("IO Exception+"+e).parent = parent. 61 .private SM1 parent. } } public MyCanvas(SM1 parent) { this. try { hc = (HttpConnection)Connector. displayForm). try { image = getImageFromUrl(" display) { if(command==exit) { Display.null). } catch(Exception err) { Alert alert=new Alert("Failure".0. } } public void commandAction(Command command. Display. err.setCurrent(alert).Graphics.EXIT.drawImage(image.1:8080/screen.1). addCommand(exit). Command.null.FOREVER).jpg"). } } } SERVER Connection Establishment & Authentication 62 .0. } } protected void paint(Graphics g) { if(image!=null) { g.TOP|Graphics.0.setCurrent(parent."Can't open the image file".getDisplay(parent).getDisplay(parent). setCommandListener(this).0. alert.printStackTrace().setTimeout(Alert.exit=new Command("Exit".LEFT). WriteLine("IPEndPoints Created"). s.InterNetwork.port2. eventPort = RDSController.WriteLine("TCPSockets Created"). eventEndPoint = new IPEndPoint(ipAddress. } internal static void BindSocket(Socket s.port1.Tcp).internal static void CreateIPEndPoints() { imagePort = RDSController.IPEndPoint ipEnd) { s. Console.Bind(ipEnd). } internal static void SetSocketOptions(Socket s) { s. Console.Any .Stream. ProtocolType. ipAddress = IPAddress. ProtocolType. imageEndPoint = new IPEndPoint(ipAddress.Stream. eventSocketListener = new Socket(AddressFamily. } internal static void StartListening(Socket s) { 63 .SendBufferSize = 100000.InterNetwork.Tcp).WriteLine("Binded Socket"). SocketType. } internal static void CreateTcpSockets() { imageSocketListener = new Socket(AddressFamily.eventPort).imagePort). Console.NoDelay = true. SocketType. if (String. Console.println("Color quantizing starts"). EventProcessor.ASCII.Accept().WriteLine("Listening Started"). } internal static void AcceptFirstConnection(Socket s) { imageSocket = s.0. "ye".None).out.canContinue = true.Accept(). true) == 0) { connectionAccepted = true. } internal static void AcceptSecondConnection(Socket s) { eventSocket = s. } } Desktop Capture & Resolution matching:internal static byte[] ColorQuantize(Bitmap bmp) { #if IMAGE System.WriteLine("Connection Accepted").s.InitializeByteArrays(). #endif 64 .Send(responseBytes. } internal static void SendResponse() { responseBytes = Encoding.WriteLine("Connection Accepted").canContinue = true.Socket Flags. Console. ImageProcessor. EventProcessor.GetBytes(response). Console.Compare(response.responseBytes. imageSocket.Listen(2).Length. byte[] bmpArray = new byte[bmp.Width * bmp.Height]; int w = bmp.Width; int h = bmp.Height; BitmapData bmpData; { byte* bmpPtr = (byte*)bmpData.Scan0.ToPointer(); for (int i = 0; i < bmpData.Height; i++) { int k = i * DesktopScreen.screenWidth ; for (int j = 0; j < bmpData.Width; j++) { bmpArray[k + j] = (byte)((32 * (bmpPtr[2] / 32)) + (4 * (bmpPtr[1] / 32)) + (bmpPtr[0] / 64)); bmpPtr += 3; } } } #if IMAGE System.out.println ("Length of the Array returned : " + bmpArray.Length ); #endif internal static byte[] ExclusiveOR(byte[] x, byte[] y) { byte[] xorBytes = new byte[DesktopScreen.screenWidth * DesktopScreen.screenHeight]; int j = DesktopScreen.screenWidth * DesktopScreen.screenHeight; for (int i = 0; i < j; i++) { 65 xorBytes[i] = (byte)(x[i] ^ y[i]); } #if IMAGE System.out.println ("EXORed Image Size : " + xorBytes.Length ); #endif return xorBytes; } internal static byte[] RLEEncoderShortBoundary(byte[] x) { #if IMAGE System.out.println ("RLE Encoder short boundary starts"); #endif int i = 0, j = 0, xl = x.Length; byte[] y = new byte[1024 * 1000]; byte f, s; ushort r = 0; f = x[i]; i += 1; s = x[i]; i += 1; while (i < xl) { if (f == s) { y[j] = f; j += 1; y[j] = s; 66 j += 1; while (i < xl) { if (f == x[i] && r < 65535) { r += 1; i += 1; } else break; } byte[] t = BitConverter.GetBytes(r); y[j] = t[0]; j += 1; y[j] = t[1]; j += 1; r = 0; if (i < xl - 1) { f = x[i]; i += 1; s = x[i]; i += 1; } else if (i == xl - 1) { y[j] = x[i]; j += 1; break; 67 Array. } else { y[j] = s.out. output.println ("RLEEncoder short boundary ends "). break.out. j += 1. j += 1. 0. i += 1. #endif #if IMAGE System. 0. j).Length).println ("Length of the Array returned : : " + output. #if IMAGE System. if (i < xl) { s = x[i].} } else { y[j] = f. } } } byte[] output = new byte[j]. f = s.ConstrainedCopy(y. } 68 . #endif return output. println ("GZipCompress ends "). GZipStream gz = new GZipStream(ms.Length). } Event Handling: class EventProcessor { #region Fields Import dmouse1.ToArray().Length.dll Import hal. #endif return ms.println ("GZipCompress starts ").println ("Length of the Array returned : " + ms. gz.ToArray(). gz. MemoryStream ms = new MemoryStream().dll Import dkey1.Close().dll internal enum MouseEventFlags { LEFTDOWN = 0x00000002.out. 0. 69 .out. #endif #if IMAGE System.Write(data. #if IMAGE System. CompressionMode. data. #endif uncompressedBufferLength = data.internal static byte[] GzipCompress(byte[] data) { #if IMAGE System. true).out. LEFTUP = 0x00000004.Length ).Compress. KeyDown. MIDDLEUP = 0x00000040. MOVE = 0x00000001. RIGHTUP = 0x00000010. Middle.NoEvent.NotAssigned . Left. ABSOLUTE = 0x00008000. internal static byte[] eventBytes = null. MOUSEWHEEL = 0x00000800 } internal enum InputEvent { NoEvent. 70 . MouseDown. KeyUp. internal static byte[] keyValueBytes = null. MouseWheel } internal enum MButton { NotAssigned. MouseUp. internal static InputEvent inputEvent = InputEvent. internal static byte[] mouseButtonBytes = null. MouseMove. RIGHTDOWN = 0x00000008. Right } internal static MButton mouseButton = MButton.MIDDLEDOWN = 0x00000020. #endregion #region Methods #region DLLImport Methods [DllImport("user32. uint dy.dll")] private static extern void keybd_event(byte bvk. mouseButtonBytes = new byte[1]. internal static byte[] mouseDeltaBytes = null. #endregion internal static void InitializeByteArrays() { eventBytes = new byte[1]. UIntPtr dwExtraInfo). internal volatile static bool canContinue = false. internal static byte[] syncBytes = null. uint dwFlags. 71 . internal volatile static bool pausedByClient = false. internal static short mouseDelta = 0. [DllImport("user32. uint dx. keyValueBytes = new byte[1]. internal static Point point. internal volatile static bool shouldExit = false. internal static short mouseXpos = 0. internal static byte[] mouseYposBytes = null. int dwData.dll")] private static extern void mouse_event(uint dwFlags. byte bScan. UIntPtr dwExtraInfo).internal static byte[] mouseXposBytes = null. internal static short mouseYpos = 0. internal volatile static bool shouldStop = false. Receive(keyValueBytes. mouseYposBytes = new byte[2]. eventBytes. syncBytes = new byte[1].None). } 72 . } internal static void ReceiveEvent(Socket s) { if (RDSSocket.println ("Receiving Event "). mouseDeltaBytes = new byte[2].Length. keyValueBytes. } if (eventBytes[0] == 1) { inputEvent = InputEvent. break.mouseXposBytes = new byte[2]. 0. 0.out.None). s.Length. SocketFlags.Available > 0) { s.KeyUp. point = new Point().Receive(eventBytes. #endif while (true) { (s.connectionAccepted ) { #if EVENT System. SocketFlags. } } else if (eventBytes[0] == 4) { inputEvent = InputEvent.Receive(mouseButtonBytes. s. SocketFlags. SocketFlags. if (mouseButtonBytes[0] == 1) { mouseButton = MButton. mouseButtonBytes. if (mouseButtonBytes[0] == 1) { mouseButton = MButton.Right. 0.None). s. s.Length.Length.else if (eventBytes[0] == 2) { inputEvent = InputEvent.Receive(keyValueBytes. 0. 0. } 73 .None).MouseDown. } else if (eventBytes[0] == 3) { inputEvent = InputEvent. } else if (mouseButtonBytes[0] == 3) { mouseButton = MButton.Receive(mouseButtonBytes.Left. mouseButtonBytes.KeyDown.Middle.MouseUp. } else if (mouseButtonBytes[0] == 2) { mouseButton = MButton.None). keyValueBytes. SocketFlags.Left.Length. MouseMove.else if (mouseButtonBytes[0] == 2) { mouseButton = MButton.None).Receive(mouseDeltaBytes.ToInt16(mouseDeltaBytes.out. 74 .X = mouseXpos. 0). mouseXposBytes.MouseWheel. mouseDelta = BitConverter. mouseYpos = BitConverter. mouseYposBytes.ToInt16(mouseYposBytes.Y = mouseYpos.println (" Received Event : " + eventBytes[0]). SocketFlags. SocketFlags. s. point. 0). 0).Length. point. 0.None). 0.None). } #if EVENT System.Right. mouseXpos = BitConverter.Length. mouseDeltaBytes.Receive(mouseXposBytes. s.Receive(mouseYposBytes.Length.ToInt16(mouseXposBytes. } else if (mouseButtonBytes[0] == 3) { mouseButton = MButton.Middle. } } else if (eventBytes[0] == 5) { inputEvent = InputEvent. 0. SocketFlags. s. } else if (eventBytes[0] == 6) { inputEvent = InputEvent. 2.1 Functional Test We have exercised the code with normal input values for which expected results were obtained.#endif 5. 5. 5.3 Structure Test In the structure test we found the exact flow of the program and tested for incremental test cases.4 Black box Test In the black box test we found that for the given input values the required output values were obtained.2.2.2 TESTING The various testing strategies used in our code are: • Functional Test • Stress Test • Structure Test • Black box Test • White box Test 5.2 Stress Test We are concerned with exercising the internal logic of the program and so we traversed particular execution paths and we exercised test cases.2. 5.5 White box Test In the white box test temporary variables were used in the functional to test the execution of the process and the required output has been obtained 75 . 5.2. The mobile client is capable of accessing system from anywhere in the world provided there is GPRS 76 . The system uses GPRS as the medium through which the communication takes place.successfully. We tested the code unit by unit and it was efficient in integrating into the required software product and finally performing the possible test scenarios performed the integration testing to the product and the perfect output was obtained without any error. CHAPTER 6 CONCLUSION AND FUTURE ENHANCEMENTS In this system the Personal Computer is accessed from remote location with just the handheld devices. Thus this makes this remote desktop accessing system practically more viable. This system requires the system to be on. CHAPTER 7 REFERENCES 1.Myers ‘Using handhelds for wireless remote control of PCs’. The performance of the system is dependent on the GPRS bandwidth available.connectivity. In the future we have proposed to enhance this feature by using the mobile itself to switch on the system and then to establish the connection. with the server running for establishing communication. Brad A. it is possible to control and perform tasks on the system from remote locations on the move. 77 . This can be done by calling on to the landline which is connected to the system and from the line a circuit is designed to induce a 5Volt trigger to boot the system on and the server is made default in the system startup services. June 2004. Thus by running the server on the system and the client application on the mobile. unlike the existing systems which just makes use of Bluetooth connectivity and limits the communication distance to few meters which is practically of little use. 3. “Inc White Paper: ‘The Emergence of PC Place Shifting’”. 4. Chung-wei Lee. CMWare. “Inc White Paper: NetOp® Mobile”. 5.2. et al. 6. Copenhagen. ‘Using handhelds and PCs together’ by’. Soma Gosh ‘MIDlet deployment: Learn to deploy remotely and locally to J2ME devices’ April 2006.. 2007. 78 . Wen-Chen Hu.Myers. Brad A. ‘Client side handheld computing and Java 2 platform Micro Edition’. September 2006. November 2001. Yapin Zhong. 79 .
https://www.scribd.com/document/86323574/Main-Pages
CC-MAIN-2017-09
refinedweb
8,902
52.36
04 October 2010 07:09 [Source: ICIS news] SINGAPORE (ICIS)--Kuwait Aromatics Co (KARO) will start selling heavy aromatics next year and is currently conducting a feasibility study on a new downstream project, the company chairman said over the weekend. “We will start offering heavy aromatics during next year. That will add more volumes to our export quantities and will increase the company’s returns,” said Bakhit Al-Rashidi in a statement dated 2 October. No further details were provided. Kuwait Paraxylene Production Company (KPCC), a wholly-owned subsidiary of KARO, currently produces 829,000 tonnes of paraxylene (PX) and 393,000 tonnes/year of benzene at its $2bn aromatics complex in ?xml:namespace> Meanwhile, KARO was looking at pursuing a downstream project that involves using PX products as feedstock, Al-Rashid said. “We are presently at the feasibility stage and aim to finalise it during 2011,” he added. KARO is a joint venture (JV) between PIC and KNPC each has a 40% stake in the JV, while QPIC owns the remaining
http://www.icis.com/Articles/2010/10/04/9398288/kuwaits-karo-to-start-heavy-aroms-sale-in-11-eyes-new-project.html
CC-MAIN-2014-35
refinedweb
172
59.33
#include <archive_entry.h> The tag specifies the principal to which the permission applies. Valid values are:. Directories have an additional ACL ( ARCHIVE_ENTRY_ACL_TYPE_DEFAULT), which controls the initial access ACL for newly created directory entries. There are four possible types of a NFSv4 ACE: The tag specifies the principal to which the permission applies. Valid values are:: The following NFSv4 ACL inheritance flags are supported: archive_entry_acl_clear() removes all ACL entries and resets the enumeration pointer. archive_entry_acl_count() counts the ACL entries that have the given type mask. type can be the bitwise-or offor POSIX.1e ACLs and separated: The following flags are effecive only on NFSv4 ACL: The following flags are effective on both POSIX.1e and NFSv4 ACL: specified,. Please direct any comments about this manual page service to Ben Bullock. Privacy policy.
https://nxmnpg.lemoda.net/3/archive_entry_acl_text_w
CC-MAIN-2019-51
refinedweb
132
50.02
new details about the type system of XPath, model...1.3.4 Fallbacks For Expressions 2.9 Conditional Expressions 2.10 Quantified Expressions 2.11 Expressions on Datatypes 2.12 Validate Expressions A Complete BNF A.1 Grammar A.2 Precedence Order A.3 Lexical structure A.3.1 Lexical States 10 Apr 2002 H.2 20 Dec 2001. ]. . Whitespace is not represented. A normative version of the EBNF that includes tokens and token states is presented in the appendix [A Complete BNF]. Note: The use of a prefix token ":" is allowed on unprefixed QNames to visually distinguish tokens that are spelled the same as keywords. For instance, the following is a path expression containing the element names "for", "if", and "return": :for/:if/:return. The value of an expression is. xf: is considered to be bound to the namespace of XPath/XQuery functions and operators, (described in [XQuery 1.0 and XPath 2.0 Functions and Operators]). In some cases, where the meaning is clear and namespaces are not important to the discussion, built-in XML Schema typenames such as integer and string will be used without a namespace prefix.: Type exception policy. This is one of the values strict or flexible. The value indicates the action that should be taken when a type exception is raised. If the policy is strict, the error value will be returned. If the policy is flexible, then a fallback conversion will be invoked; the error value will be returned only if the fallback conversion fails.. In-scope variables. This is a set of (QName, type) pairs. It defines the set of variables that have been declared and are available for reference within the XPath expression. The QName represents the name of the variable, and the type represents its static data type., the filter expression E1[E2], and the ordering expression E1 sortby, E1[E2] or E2 sortby an expression E1/E2, E1[E2], or E1 sortby, E1[E2], or E1 sortby E2 is evaluated, the context size as the base for any rooted path expression, as well being used implicitly a point in time during processing of a query. It can be retrieved by the xf:currentPath has three functions that provide access to input data. These functions are of particular importance because they provide the only way in which an expression can reference a document or a collection of documents. The three-dependent. For instance, function returns the input sequence. For example, the expression input()//customer returns all the customer elements that are descendants of nodes in the input sequence. If no input sequence has been bound, the input function returns the error value. The collection function returns the nodes found in a collection. A collection may be any sequence of nodes. A collection is identified by a string, which must be a valid URI. For example, the expression collection("")//customer identifies all the customer elements that are descendants of nodes found in the collection whose URI is. The document function, when its first argument is a string containing a single URI that refers to an XML document, returns the root of that document. The document function can also be used to address multiple documents or document fragments; see [XQuery 1.0 and XPath 2.0 Functions and Operators] for details. XPath are processed. For each expression, the operands and result are instances of the Data Model. The details of transforming XML documents into the Data Model are described in [XQuery 1.0 and XPath 2.0 Data Model]. Transformation of a Data Model instance into an XML document is currently an open issue.. XPath is a strongly typed language with a type system based on [XML Schema]. The built-in types of XPath include the node kinds of XML (such as element, attribute, and text nodes), the built-in atomic types of [XML Schema] (such as xs:integer and xs:string), and the following special derived types: xs:dayTimeDuration and xs:yearMonthDuration (described in [XQuery 1.0 and XPath 2.0 Functions and Operators]). When the type of a value is not appropriate for the context in which it is used, a type exception is raised. Languages that are based on XPath 2.0 may handle type exceptions with either a strict or a flexible policy, as described in 2.1.3.4 Fallbacks. Like XML Schema, XPath distinguishes named types from anonymous types. The set of named types includes all the built-in types and all user-defined simple or complex types for which the type declaration contains a name. Named types are associated with values in one of the following ways: A literal value has a named type; for example, the type of the value 47 is xs:integer. The constructor functions described in [XQuery 1.0 and XPath 2.0 Functions and Operators] return values with named types; for example, xf:date("2002-5-31") returns a value of type xs:date. When an instance of the Data Model is constructed from a validated document, type names assigned by a schema processor are preserved in the Data Model. The validate expression invokes schema validation within a query, assigning type names in the same way that a schema processor would. The cast expression creates an atomic value with a specific named type. Some functions, such as data(), extract typed values from the nodes of a document, preserving the named types of these values. The XPath type system is formally defined in [XQuery 1.0 Formal Semantics]. This section presents a summary of types from a user's perspective. XPath, static. exception is raised..6.1 Value Comparisons. Type conversions sometimes depend on a process called atomization, which is used when an optional atomic value is expected. When atomization is applied to a given value, the result is either a single atomic value, an empty sequence, or a type exception. Atomization is defined as follows: If the value is a single atomic value or an empty sequence, atomization simply returns the value. If the value is a single node, the typed value of the node is extracted and returned; however, if the typed value is a sequence containing more than one item, a type exception is raised. In any other case, atomization raises a type exception. The action taken when a type exception is raised depends on the language environment in which the XPath expression is being evaluated. A language environment may choose either a strict or a flexible type exception policy. If the policy is strict, a type exception is treated as an error. If the policy is flexible, the language environment must handle type exceptions by applying a fixed set of rules called fallback conversions. The purpose of fallback conversions is to provide backward compatibility with the behavior of XPath Version 1.0. type exception is raised when a given value does not conform to its required type. A language environment that implements fallback conversions must resolve this conflict by applying the following rules, in order: If the required type is anything other than an atomic type or a single node, the error value is, the error value is returned.. XPath also allows variables to be bound in the host language environment. parameters in the function's signature; otherwise a static error is raised. A function call expression is evaluated as follows: Each argument expression is evaluated, producing an argument value. Each argument value is converted to the declared type of the corresponding function parameter, using the function conversion rules listed below. The function is executed using the converted argument values. The result is a value of the function's declared return type. The function conversion rules are used to convert an argument value to its required type; that is, to the declared type of the function parameter. The required type is expressed as a SequenceType. The function conversion rules are as follows: If the required type is an AtomicType: Atomization is applied to the given value. If the resulting atomic value is of type xs:anySimpleType, an attempt is made to cast it to the required type; if the cast fails, the function callPath comments can be used to provide informative annotation. These comments are lexical constructs only, and do not affect the processing of an expression. Comments may be used before and after major tokens within expressions . See A.3 Lexical structure for the exact lexical states where comments are recognized. Ed. Note: The EBNF here should disallow "--}" within the comment, rather than "}". A path expression locates nodes within a tree, and returns a sequence of distinct nodes in document order. A path expression is always evaluated with respect to an evaluation context. There are two kinds of path expressions: relative. Since the self axis always contains at most one node, it makes no difference whether it is a forward or reverse axis. is a QName is true if and only if the kind of the node is the principal node kind and the expanded-name of the node is equal to the expanded-name specified by the QName. For example, child::para selects the para element children of the context node; if the context node has no para children, it selects an empty set of nodes. attribute::href selects the href attribute of the context node; if the context node has no href attribute, it selects node kind whose expanded-name. Qualifiers are of two general forms: predicates, which are used to filter a node sequence by applying some test, and dereferences, which are used to map reference-type an inner an atomic value of a numeric type, the predicate truth value is true if and only if the value of the predicate expression is equal to the context position. If the value of the predicate expression is an atomic value of type Boolean, the predicate truth value is equal to the value of the predicate expression. If the value of the predicate expression is a sequence that contains at least one node and does not contain any item that is not a node, the predicate truth value is true. The predicate truth value in this case does not depend on the content of the node(s). [Ed. Note: This rule is pending approval by the XSLT Working Group.] In any other case, a type exception is raised.] following-sibling::chapter[position()=1]selects the next chapter sibling of the context node preceding-sibling::chapter[position()=1]selects the previous chapter sibling parachildren an list based on nodeid. If an operand of union, intersect, or except contains an item that is not a node, the error value is. An arithmetic expression is evaluated by applying the following rules, in order, until an error is encountered or a value is computed: Atomization is applied to each operand, resulting in a single atomic value or an empty sequence for each operand. If either operand is an empty sequence, the result of the operation is an empty sequence. If an operand has the type xs:anySimpleType, it is cast to xs:double. If the cast fails, the error value is returned. If the two operands have different types, and these types can be promoted to a common type using the promotion rules in B.1 Type Promotion, the operands are both promoted to their least common type. For example, if the first operand is of type hatsize which is derived from xs:decimal, and the second operand is of type shoesize which is derived from xs:integer, then both operands are promoted to the type xs:decimal. If the operand type(s) are valid for the given operator, the operator is applied to the operand(s), resulting in an atomic value or an error (for example, an error might result from dividing by zero.) The combinations of atomic types that are accepted by the various arithmetic operators, and their respective result types, are listed in B.2 Operator Mapping. If the operand type(s) are not valid for the given operator, a type exception is raised. Here are some examples of arithmetic expressions: In general, arithmetic operations on numeric values result in numeric values: ($salary + $bonus) div 12 Subtraction of two date values results in a value of type xs. Value comparisons are intended for comparing single values. The result of a value comparison is defined by applying the following rules, in order: Atomization is applied to each operand, resulting in a single atomic value or an empty sequence for each operand. If either operand is an empty sequence, the result is an empty sequence. If either operand has the type xs:anySimpleType, that operand is cast to a required type, which is determined as follows: If the type of the other operand is numeric, the required type is xs:double. If the type of the other operand is xs:anySimpleType, the required type is xs:string. Otherwise, the required type is the type of the other operand. If the cast fails, the error value is returned. If the value comparison has two numeric operands of different types, one of the operands is promoted to the type of the other operand, following the promotion rules in B.1 Type Promotion. For example, a value of type xs:integer can be promoted to xs:decimal, and a value of type xs:decimal can be promoted to xs:double. exception is raised. Here are some examples of value comparisons: earlier than the second operand node in document order and is not an ancestor of the second node; otherwise it returns false. A comparison with the follows operator returns true if the first operand node is later than the second operand node in document order and is not an descendant of the second node;. In the absence of errors, the value of a logical expression is always one of the boolean values true or false. The first step in evaluating a logical expression is to reduce each of its operands to an effective boolean value, which is true, false, or the error value. The effective boolean value of an operand is defined as follows: If the operand is an empty sequence, its effective boolean value is false. If the operand is an atomic value of type xs:boolean, the operand serves as its own effective boolean value. If the operand is a sequence that contains at least one node and does not contain any item that is not a node, its effective boolean value is true. [Ed. Note: This rule is pending approval by the XSLT Working Group.] In any other case, a type exception is raised. The value of an and-expression is determined by the effective boolean values (EBV's) of its operands, according to the following table: The value of an or-expression is determined by the effective boolean values (EBV's) of its operands, according to the following table: The order in which the operands of a logical expression are evaluated is implementation-dependent. The tables above are defined in such a way that an or-expression can return true if the first expression evaluated is true, and it can return the error value if the first expression evaluated contains an error. Similarly, an and-expression can return false if the first expression evaluated is false, and it can return the error value if the first expression evaluated contains an error. As a result of these rules, the value of a logical expression is not deterministic in the presence of errors, as illustrated in the examples below. Here are some examples of logical expressions: The following expressions return true: 1 = 1 and 2 = 2 1 = 1 or 2 = 3 The following expression may return either false or the error value: 1 = 2 and 3 div 0 = 47 The following expression may return either true or the error value: 1 = 1 or 3 div 0 = 47 The following expression returns the error value: 1 = 1 and 3 div 0 = 47 In addition to and- and or-expressions, XPath. If the effective boolean value of its operand is the error value, not returns the error value. The not function is described in [XQuery 1.0 and XPath 2.0 Functions and Operators]. Ed. Note: Functions named and3, or3, and not3may be provided to implement three-valued logic. See Issue 28. X, as defined in 2.7 Logical Expressions. FLWR.7 Logical Expressions. return an error as soon as it finds one binding tuple for which the test expression returns an error. Similarly, if the quantifier is every, an implementation may return false as soon as it finds one binding tuple for which the test expression has an effective Boolean value of false, and it may return an error as soon as it finds one binding tuple for which the test expression returns return either true or the error value, since its test expression returns true for one variable binding and the error value for another: some $x in (1, 2, "cat") satisfies $x * 2 = 4 This quantified expression may return either false or the error value, since its test expression returns false for one variable binding and the error value for another: every $x in (1, 2, "cat") satisfies $x * 2 = 4 SequenceTypes occur explicitly in several kinds of XPath expressions. The boolean operator instance of returns true if the value of its first operand matches the type named in its second operand, according to the rules for SequenceType Matching; otherwise it returns false. Examples: $x instance of element of type animal This example returns true if the value associated with variable $x is an element whose content is a value of the type animal. <a>5</a> instance of xs:integer This example returns false because the given value is not an integer; instead, it is an element whose value is an integer. <a>5</a> instance of element of type xs:integer This example returns true because the given value matches the given type according to the rules for SequenceType Matching. Occasionally it is necessary to convert a value to a specific datatype. For this purpose, XPath provides a cast expression that creates a new value of a specific type based on an existing value. A cast expression takes two operands: an input expression and a SequenceType, called the target type. The cast expression first performs atomization on its input expression, resulting in a single atomic input value or the empty sequence. If the input value is the empty sequence, the cast expression returns an empty sequence. Otherwise, the cast expression creates a new instance of the target type that is equal to the input value. The type of the input value is called the input type. cast is supported only for certain combinations of input type and target type, as listed below: cast is supported for the combinations of input type and target type listed in [XQuery 1.0 and XPath 2.0 Functions and Operators]. For each of these combinations, both the input type and the target type are primitive schema types. For example, a value of type xs:string can be cast into the type xs:decimal. A value of a derived atomic type can always be cast into its base type. For example, if the type shoesize is derived by restriction from the type xs:integer, a value of type shoesize can always be cast into the type xs:integer. For any combination of input type and target type that is not in the above list, a cast expression returns the error value. If the input value is not in the value space of the target type, the error value is returned. A cast expression also returns the error value if any facet of the target type is not satisfied. For example, cast as xs:integer($x) returns the error value if the value of $x is 4.99 because this value cannot be represented with zero fractional digits. Note: The working group has declared an intention to support casts to user-defined target types, subject to certain restrictions. Work is in progress to define the semantics of these casts. In addition to cast, XPath provides type-checking expressions called treat and assert. Each of these expressions takes two operands: an expression and a SequenceType. Unlike cast, however, treat and assert do not change the type or value of their operands. Instead, the purpose of a treat or assert expression is to ensure that its operand has an expected type. Each of these expressions has semantics that are applied during static type-checking, and additional semantics that are applied during expression evaluation. If static type checking is disabled or not supported, only the run-time semantics of treat and assert apply. The semantics of the two expressions are as follows: Semantics of treat as type1 (expr2): During static type checking: type1 must be a subtype of the static type of expr2, using the definition of subtype in [XQuery 1.0 Formal Semantics]--otherwise, a static [id-sequencetype], the treat expression returns the value of expr2; otherwise, it returns the error value. the error value is returned. Semantics of assert as type1 (expr2): During static type checking: The static type of expr2 must be a subtype of type1, using the definition of subtype in [XQuery 1.0 Formal Semantics]--otherwise, a static error is raised. The static type of the assert expression is type1. assert provides a stronger static type guarantee than treat. During expression evaluation (at "run-time"): If expr2 matches type1, using the SequenceType Matching rules in [id-sequencetype], the assert expression returns the value of expr2; otherwise, it returns the error value. If the value of expr2 is returned, its identity is preserved. If the assert expression has passed static type checking without an error, and expr2 does not return an error, then the assert expression will never return the error value at run-time. Example: assert as element of type USAddress ($myaddress) The static type of $myaddress must be element of type USAddress or one of its proper subtypes, and at run-time, the value of $myaddress must match the type element of type USAddress using SequenceType Matching rules; otherwise the error value is node that has a parent is validated, the parent of the original node will not be the parent of the validated node. To allow locally declared elements and attributes to be validated, a schema context may optionally be specified. If no context is specified, all top-level names in the material to be validated are treated as global names. series of steps: Serialize the value of the expression, using xsi:type attributes to indicate the types of elements that have type annotations or that contain a single atomic value of a known type (however, do not generate an xsi:type attribute for any element that already has such an attribute). Invoke schema validation on the resulting serialized expression, using the in-scope schema definitions. Remove any xsi:type attributes that were generated in Step 1. in po:purchaseOrder {$x} validates the value of $x in the context of the global element declaration po:purchaseOrder. Suppose that $y is bound to an productName element. Then validate in po:purchaseOrder/items/item {$y} validates the value of $y in the context of an item element, inside an items element, inside the global element declaration po:purchaseOrder. Suppose that $z is bound to a zip element. Then validate in type po:USAddress {$z} validates the value of $z in the context of the global type declaration po:USAddress. Under certain circumstances, validation of an element or attribute may result in the loss of some type information. The following examples illustrate some of these circumstances: validate { <sizes>{1, 2, 3}</sizes> } The constructed <sizes> element node has no type annotation. Its value is a sequence of integers, but "sequence of integers" is not a built-in type that can be represented by an xsi:type attribute. The effective serialized value to be validated is <sizes>1 2 3</sizes>. After validation, if no more specific type is found, the value of the <sizes> element will be " 1 2 3", an instance of xs:anySimpleType. validate { <animal>{ "A cat", "named Oscar" }</animal> } The constructed animal element node has no type annotation. Its value was derived from two strings, but the boundaries between the strings will be lost during validation. The effective serialized value to be validated is <animal>A cat named Oscar</animal>. If animal is a global element declared to have xs:string as its type, the validated value of the element will consist of a single string. On the other hand, if the declared type of animal is xs:string*, the validated value of the element will consist of the following four strings: " A", " cat", " named", and " Oscar". validate { <mixture>{ 1, "2", "three" }</mixture> } The constructed <mixture> element node has no type annotation. Its typed value consists of an integer and two strings, but there is no possible schema type that can be assigned to the element node that will preserve this type information. The effective serialized value to be validated is <mixture>1 2 three</mixture>. After validation, the value of the <mixture> element might be two integers and a string, or three strings, or one string. validate { <shoe size="{7}"/> } The constructed size attribute node has no type annotation. Its value is an integer, but there is no way to represent the type of a serialized attribute. The effective serialized value to be validated is <shoe size="7"/>. After validation, if no more specific type is found, the value of the size attribute will be " 7", an instance of xs:anySimpleType.. Ed. Note: It is likely that the Working Groups will specify a system of built-in precedence in future drafts, at least for the normative BNF in this appendix. It is recognized that the current table-driven approach contains some bugs. In the following table, operators with a higher precedence number are more tightly bound than operators with a lower precedence number. Operators listed at the same level are evaluated from left to right. A token as defined by this specification is a lexical unit specified by the TERMINALS section. A token symbol is the symbolic name given to that token. A token part is the most atomic part of a token. For instance, AxisDescendantOrSelf has two token parts, "descendant-or-self" and "::". For readability, Whitespace may be used in expressions even though not explicitly allowed by the grammar: Whitespace may be freely added between tokens and token parts, lexical state is a condition that is created by a previous token, or else is the starting state of the lexer. Tokens are often only recognized in a specific lexical state, and a token in turn may cause the lexer to transition to a different state. The details of these state transitions are given in the section on Lexical States. When tokenizing, the longest possible token is always returned that would be valid in the current syntactic context.. If there is an ambiguity between two tokens that isn't resolved by the longest match rule, the token that has a lower grammar number is more overrides a token with a higher grammar number. All keywords and tokens are case sensitive. ExprComment tokens should be ignored by the parser.. Under certain circumstances, an atomic value can be promoted from one type to another. The promotion rules listed below are used in basic type conversions (see 2.1.3.3 Type Conversions) and during processing of arithmetic expressions (see 2.5 Arithmetic Expressions) and value comparisons (see 2.6.1 Value Comparisons). The rules may be applied transitively. For example, since xs:integer is promotable to xs:decimal and xs:decimal is promotable to xs:float, it follows that xs:integer is promotable to xs:float, without necessarily passing through the intermediate xs:decimal type. The following type promotions are permitted: A value of type xs:decimal can be promoted to the type xs:float. A value of type xs:float can be promoted to the type xs:double. A value of a derived type can be promoted to its base type. As an example of this rule, a value of the derived type xs:integer can be promoted to its base type xs:decimal. The tables in this section list the combinations of datatypes for which the various operators of XPath are defined. For each valid combination of datatypes, the table indicates the function(s) that are used to implement the operator and the datatype. In the following tables, the term numeric refers to the types xs:integer, xs:decimal, xs:float, and xs:double. When the result type of an operator is listed as numeric, it means "same as the highest type of any input operand, in promotion order." For example, when invoked with operands of type xs:integer and xs:float, the binary + operator returns a result of type xs:float. the policy for handling type exceptions is flexible: that is, that the software attempts wherever possible to perform conversions from the supplied type of a value to the type required by the operation or function where it is used. is now a decimal, so 10 div 4 returns 2.5 (this is a change from the December 2001 working draft). Operations that previously returned positive or negative infinity, such as 10 div 0, will now return the error value. In XPath 1.0, such expressions were sometimes used as arguments to the substring() function. an empty the empty string, as it did in XPath 1.0.] . Decision by: xpath-tf on 2001-12-18 ([link to member only information] ) Decision by: xquery on 2001-12-19 ([link to member only information] ) confiriming that no action is required by the XQuery WG XSLT WG agrees that empty sequence should be used to represent missing data (this is the status quo). Should the 3-valued logic functions be part of the XPath function library? Note that they can be implemented as user functions (not as efficient as a "native" implementation). We may want to include the user definition as an example.. Decision by: xpath-tf on 2001-12-18 ([link to member only information] ) Allow them; especially in view of consistency with eg "for" that already allows them. The semantics should be the same.] . Addressed by the "Named Typing" proposal.] . Addressed by the "Named Typing" proposal. This is related to [link to resolved issue: ] . Addressed by the "Named Typing" proposal. Does the definition of a type include both element-names and element-contents (as in the Formal Semantics document), or only element-contents (as in XML Schema)? Addressed by the "Named Typing" proposal.. Addressed by the "Named Typing" proposal.? Addressed by the "Named Typing" proposal.") The semantics of the instanceof operator are not defined over all operands, e.g. sets of several nodes, sequences of several values, etc. What should the symantics be for these types? Should these semantics be defined in the F&O document? Element & attribute nodes ~~~~~~~~~~~~~~~~~~~~~~~~~~ Given $e is a single element or attribute node: 1. If $e is of unknown type and has simple content (i.e., $e does not contain complex content and $e does not have a known type), then data($e) evaluates to the simple content of the node and has UnknownSimpleType. Example: let $e := <fact about="what i saw"> I saw 8 cats.</ fact> return data($e) ==> "I saw 8 cats" : UnknownSimpletype data($e/@about) ==> "what i saw" : UnknownSimpleType 2. Else if $e is of a known simple type or has a simple content type, then data($e) evalutes to the simple value of the node and has the node's known simple type. Example: let $e := <weight units="{ 'lbs.' }">{ 42 }</weight> return data($e) ==> 42 : xs:integer data($e/@units) ==> "lbs." : xs:string 3. Else if $e is of an unknown (complex) type, then data($e) evaluates to string($e) (text node aggregation) and has UnknownSimpleType. let $e := <fact>The cat weighs <weight>12</weight> pounds</fact> return data($e) ==> "The cat weighs 12 pounds" : UnknownSimpleType 4. Else if $e is of a known complex type with complex or mixed content, then there are two options: 4a. data($e) evaluates to an error 4b. data($e) is defined as in (3) above. Example: Assume we have schema type: <element name="fact" mixed="true"> <element name="weight" type="xs:integer"/> </element> and $e is validated w.r.t. the above type: let $e := validate as element fact (<fact>The cat weighs <weight>12</weight> pounds</fact>) return data($e) 4a. raises error 4b. "The cat weighs 12 pounds" : UnknownSimpleType Text nodes ~~~~~~~~~~~ 5. Given $t is a single text node, then data($t) evaluates to string($t) (content of text node) and has UnknownSimpleType. Example: let $e := <fact>The cat weighs 12 pounds</fact>, $t := $e/text() return data($t) ==> "The cat weighs 12 pounds" : UnknownSimpleType NB: Open issue as to whether data() should be defined on node sequences. NB: Current definition of data() applied to a text node is the empty sequence. Comment, PI, Namespace nodes ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 6. Given $c is a comment, processing instruction, or namespace node, then data($c) evaluates to the empty sequence. Example: let $c := <!-- a comment --> return data($c) ==> () : empty Decision by: xpath-tf on 2002-03-19 ([link to member only information] ) Decision by: xquery on 2002-03-20 ([link to member only information] ) Decision by: xsl on 2002-03-28 ([link to member only information] ) Mary's proposal was adopted. In particular, we chose option (4a) instead of (4b), because the current semantics applies data() implicitly in the basic conversion rules (e.g., when implementing equality and inequality operators), and therefore (4a) will raise an error if a user attempts to extract the atomic data from an element that has *known* complex type.. Decision by: xsl on 2002-01-22 ([link to member only information] ) The XSL WG felt that these operators should operate on nodes only and not be overloaded to work on "values" as well. Functions should be used for the "analogous" functionality on values. Action to Ashok to write a proposal. It was noted that one might well want to to a "value" union operating on nodes (where the typed value of each is extracted). Decision by: xsl on 2002-01-22 ([link to member only information] ) Decision by: xquery on 2002-02-28 ([link to member only information] )Xquery acceptance of XSL proposal These operators operate on nodes only and are not overloaded to work on "values" as well. Functions are to be used for the "analogous" functionality on values.. Decision by: xquery on 2002-03-27 ([link to member only information] ) XML Query WG has adopted a solution to Issues 259 and 91 as per Proposal 1 in Michael Rys' proposal. See #unknown-simple-type-arithmetic Decision by: xsl on 2002-03-28 ([link to member only information] ) In XPath, <book><title> Mark Twain </title></book> and <book><author> Mark Twain </author></book> are treated as equal in comparisons. Is this acceptable for us? Do we need another notion of deep equality? If so, what are the compatibility issues with XPath?? [link to member only information] : null-aggregates-on-empty: Aggregate functions on empty sequences [link to member only information] Status: The XPath TF recommends that we reopen this issue. We will do a straw poll with the WG on this recommendation. The Chair views the public pushback we have received on this topic as sufficient reason for re-opening this issue: (point 8) Paul Cotton - Do we re-open this issue? Straw poll taken - Yes: 10 No: 0 Abstain: 8 The XPath TF should take this matter back under review. Action A-87-06 - Paul Cotton to convey to XPath TF that issue is re-opened and the WG would like to receive some proposed changes. As in SQL, count(()) returns 0, and all other aggregate functions return the empty sequence. This rule is familiar to SQL users and minimizes the complexity of SQL-based XQuery implementations. Decision by: xpath-tf on 2002-01-29 ([link to member only information] ) Decision by: xquery on 2002-03-06 ([link to member only information] ) Decision by: xsl on 2002-04-04 ([link to member only information] ) Change semantics of sum() on () to 0.. isand isnotinstead of ==and !==. Should we use is and isnot instead of == and !==. Using keywords would be clearer, and less prone to error. On the other hand, introduction of more keywords could cause more controversy. At Reston F2F, we agreed to infix operators 'value=', 'value<', 'node=', 'node<'. Next WD should reflect this decision. Text is in Working Draft 2001-11-28 sec 2.6.2. Decision by: xsl on 2002-02-28 ([link to member only information] )(joint meeting) Decision by: xquery on 2002-02-28 ([link to member only information] )(joint meeting) Decided to change to "is" and "isnot". An extensibility mechanism needs to be defined that permits XQuery to access a library of functions written in some other programming language such as Java. Some sources of information: the definition of external functions in SQL, the implementation of external functions in Kweelt. Should we say something about the fact that XPath is meant to be a abstract specification? I am concerned about people getting the impression that XPath can be used by itself. Maybe it can be, and maybe this is OK. [link to member only information] Paul Cotton: [link to member only information] Michael Rys: Decision by: xquery on 2002-01-16 ([link to member only information] ) Action to Michael Rys to propose alternative text to resolve issue. Decision by: xquery on 2002-01-23 ([link to member only information] ) XQuery WG approves wording in: [link to member only information] with a change so that "cannot" is changed to "should not" and Paul Cotton to convey changes to the XPath TF and XSL WG. Note: This text should be added to a new Conformance section in the XPath 2.0 specification. Thus the proposed text is:. Specifications that set conformance criteria for their use of XPath should not change the syntactic or semantic definitions of XPath as given in this specification. Decision by: xpath-tf on 2002-03-05 ([link to member only information] ) There is great concern in the XSL WG about the proposed last sentence. An alternative one was accepted by the XPath TF for approval by the WGs: Specifications that set conformance criteria for their use of XPath must not change the syntactic or semantic definitions of XPath as given in this specification; except by subsetting and/or extensions in compatible ways. Decision by: xquery on 2002-03-13 ([link to member only information] )Accepting the XPath TF proposal Decision by: xsl on 2002-04-04 ([link to member only information] ). Decision by: xquery on 2002-02-06 ([link to member only information] ) The current WD text reflects suggestions.. Decision by: xsl on 2002-01-22 ([link to member only information] ) Decision by: xquery on 2002-02-28 ([link to member only information] ) Acceptance of text in December 2001 published Working Draft.. How are collections of documents named and addressed in queries? How are they associated with files in directory structures, or resources in various systems? How does one address documents within collections? Should small set of functions on nodes, i.e., data(), name, uri-namespace(), be defined on node sequences and have an implicit mapping semantics?, e.g., data(a/b) Do we still need fallbacks if we have a marker for untyped data (="PCDATA")? [link to member only information] Mary F. Fernandez: Cf. Always explicit cast? Decision by: xsl on 2002-01-22 ([link to member only information] ) Acceptance of text in December 2001 published Working Draft. Text is in Working Draft 2001-11-28 sec 2.5. I discussed this issue with Mary on the phone today, and we have developed the following modified version of her original proposal. The key difference is this: 1. In the data model, the type name 'anySimpleType' is used everywhere that 'unknownSimpleType' was used in her original proposal. This avoids the problems discussed in: 2. In the SequenceType production, the keyword 'unknown' matches values whose most specific type is 'anySimpleType'. Jonathan and Mary ================= This message proposes, in summary, that XQuery/XPath must have a type for Text Nodes, denoted by the reserved word 'text', and a type for Atomic Values with unknown simple type, denoted by the type name 'anySimpleType' in the Data Model. In the SequenceType production, the keyword 'unknown' matches values whose most specific type is 'anySimpleType'. Rationale: XQuery/XPath supports expressions that yield two *distinct* types of values: 1. Text nodes, which have identity and contain character data Example: let $e := <fact>I saw 8 cats</fact> return $e/text() This expression yields a Text Node (that has identity!) with type 'text'. 2. Atomic values with unknown simple type, which no not have identity and contain character data Example 1: let $e := <fact about="what I saw">I saw 8 cats</fact> return data($e) This expression yields an Atomic Value (that does not have identity!) with type 'anySimpleType' Example 2: data($e/@about) This expression also yields an Atomic Value with anySimpleType. In a typed language, every value must have an associated type. Neither value above currently has a type in XQuery/XPath. In addition, Text Nodes and Atomic Values with unknown simple type do not denote the same set of values, therefore, they must have distinct types. Both these types may occur wherever a type expression is permitted, e.g., in the SequenceType production. However, note that the type name 'anySimpleType' matches all simple types, since they are all derived from 'anySimpleType', whereas the keyword 'unknown' matches only values whose most specific type is 'anySimpleType'. The formal semantics already constructs core expressions that require both 'text' and 'unknown'. for example, here's the rule that converts a node to an optional atomic value of type xsd:integer: typeswitch (Expr) as $v case xs:integer? return $v case unknown return cast as xs:integer ($v) case node return typeswitch (data($v)) as $w ... We use the type 'anySimpleType' for simple types because this type explicity captures the notion that it is a simple type for which there is no more specific known type. To simplify processing, we map all PSVI representations of character data with unknown type onto this one type. Since our language needs a way to match only values whose most specific type is 'anySimpleType', we add a keyword to the language, rather than invent a new type for XML Schema. The functionality we need is part of our language, not part of the XML Schema type system that underlies our type system. The necessity of associating a type to text nodes was first discussed in Aug 2001: Decision by: xquery on 2002-03-27 ([link to member only information] ) XML Query WG has resolved issue 174 and Strawman Issue 17 by adopting Proposal #1 Jonathan Robie's proposal above. Decision by: xsl on 2002-03-28 ([link to member only information] ) The proposal by Michael Rys in [link to member only information: Proposal to close issue expr[nodes]] treats not()/not3() differently from all other functions that take a boolean formal argument. Cf. Implicit conversion of node-sets to boolean for comparisons.. See [link to member only information] . Decision by: xpath-tf on 2002-01-22 ([link to member only information] )Accepting Don's Proposal Decision by: xsl on 2002-01-22 ([link to member only information] )(whole group at XPath TF telcon) Decision by: xquery on 2002-01-23 ([link to member only information] )Accepting Don's Proposal Decision by: xquery on 2002-02-06 ([link to member only information] )... Addressed by the "Named Typing" proposal. What should be the ordering of the results of the union, intersect, and except operators? Issue is for material in sec 2.4. in Working Draft 2001-11-28. Union, intersect, and except on node sequences are defined to return their results in document order. What arithmetic operations should be supported on date/time types? Issue is for material in sec 2.5. in Working Draft 2001-11-28. Decision by: xquery on 2002-02-06 ([link to member only information] ) Locus should be Functiond and Operators Make sure that the XPath/XQuery document is consistent with the F&O document with respect to the supported combinations of types for comparison operators. Issue is for material in sec 2.6. in Working Draft 2001-11-28.. Addressed by the "Named Typing" proposal. The current Datatype production supports declarations of the form "element of type <var>". Do we also need declarations of the form "attribute of type <var>" or "node of type <var>"? Issue is for material in sec 2.13. in Working Draft 2001-11-28. Addressed by the "Named Typing" proposal. Does the Datatype declaration need a way to specify both the QName of an element or attribute and its type, eg element person of type plumber? Issue is for material in sec 2.13. in Working Draft 2001-11-28. Addressed by the "Named Typing" proposal. Should XQuery support the import of locally declared types from schemas? Issue is for material in sec 2.13. in Working Draft 2001-11-28. Addressed by the "Named Typing" proposal.. [!] How do namespace declarations in the prolog and in namespace declaration attributes affect the in-scope namespaces of the context? Issue is for material in sec 3. in Working Draft 2001-11-28. Decision by: xpath-tf on 2002-01-15 ([link to member only information] ) Decision by: xquery on 2002-01-16 ([link to member only information] ) Decision by: xsl on 2002-01-22 ([link to member only information] ) [Decided modulo suggested changes to text by Mike K] Action Item on Jonathan to incorporate these changes.". Decision by: xpath-tf on 2002-01-15 ([link to member only information] ) Decision by: xquery on 2002-01-16 ([link to member only information] ) Decision by: xsl on 2002-01-22 ([link to member only information] ) [Decided modulo suggested changes to text ] Action Item on Jonathan to incorporate these changes. "any sequence" or "any type" Do we want to continue to support both of the following forms for computed attribute values? If not, is it possible to decide which to remove? <pic size={}> { } </pic> <pic size="{}"> { } </pic> Decision by: xquery on 2002-01-16 ([link to member only information] ) Jonathan: Computed attribute values - two ways to do this. Propose to elimiate no quoted representation. Michael: a = {3} - it is clear that the type is integer... PaulC: Is there anyone who thinks the semantics are different. Michael is not sure. PaulC: Anyone think we should retain non quoted syntax: no objections, resolved.? Addressed by the "Named Typing" proposal. How do you get strings such as single and double quote to be allowed in character strings? <name>Ben & Jerry's</name> eg should doubling a quote escape it? It would seem that we need to allow these CharRef's in string literals as well. Would we prefer a syntax that requires explicit declaration of a general type when a function is to be loosely typed, rather than use the current syntax in which the type is omitted when the function is untyped.? What is the result of applying the data() function on a SimpleValue? Is it an error, is it a no-op, or is it a type exception with a fallback? Decision by: xpath-tf on 2001-12-18 ([link to member only information] ) Decision by: xquery on 2001-12-19 ([link to member only information] ) data() applied to simple value is identity function (no-op). Rationale: does not require special 'fallback' behavior and if we resolve Issue 0172 so that data is defined on node sequences, then for consistency, it should be defined on heterogeneous sequences. Still waiting on general proposal for Issue 172.. Given the expression: cast as xsd:decimal(//element_string [3]) div cast as xsd:decimal("+1.25000000") and a type of ELEMENT element_decimal [xsd:string] for the element_string nodes, our current cast rules disallow the cast of the element node to a value, since the above expression would be translated into: data(cast as xsd:decimal(//element_string [3])) div cast as xsd:decimal("+1.25000000") instead of (the user expected): cast as xsd:decimal(data(//element_string [3])) div cast as xsd:decimal("+1.25000000") Could we change the casting rules to allow the above? We could either add a rule that pushes data() into cast expressions or have a special rule for casting to simple value types that implies applying data() in the casted expression (similar to arithmetic expressions). Addressed by the "Named Typing" proposal. User defines a derived type, what operators are inherited by that type. SQL has a concept of distinct type. A distinct type does not inherit the operastors on the base type. XQuery in F&O does the opposite. All operations on the base type are inherited. [link to member only information] Don Chamberlin: [link to member only information] Don Chamberlin: MR: Why does collection() return item*. I want document*. JR: You can specify what you want. You have to accept a URI and what you return is implementation dependent. SCA: Strawpoll. 5 item*, 3 document*. No one cannot live with item* Can an implementation provide a more specific return type than item* and still be a conforming implementation? Some discussion. No consensus.? Currently, the arithmetic operation rules in [1] say: The operands of an arithmetic expression do not have required types. An arithmetic expression is evaluated by applying the following rules, in order, until an error is raised or a value is computed: 1. If any operand is a sequence of length greater than one, a type exception is raised. 2. If any operand is an empty sequence, the result is an empty sequence.. 4. If any operand is an untyped simple value (such as character data in a schemaless document), it is cast to the type suggested by its lexical form. For example, the untyped value 12 is cast to the type xs:integer.. Rule 4 cannot be efficiently implemented and basically would defer any algebrization of the operation to the runtime when the value is actually available to make this decision. Not even XPath 1.0 had such an impossible rule. (see also Mary's reply in [2]) Instead, I would like to align this with the rules of comparison operators in the following way: The untyped simple value is cast to the type of the other operand. If both operands are untyped, they are cast to double (in analogy to the XPath 1.0 number conversion). E.g., unknownSimpleType + xsd:decimal will become cast as xsd:decimal (unknownSimpleType) + xsd:decimal. unknownSimpleType + unknownSimpleType will be cast as xsd:double (unknownSimpleType) + cast as xsd:double (unknownSimpleType). Another proposal was provided by Michael Kay in [3] that however relays on the not yet introduced type numeric [4], thus I think we should follow the rule above (which is basically the same as we do for comparisons). [1] [2] [link to member only information] [3] [link to member only information] [4] [link to member only information] I have been tasked with rewording the sections 2.5 and 2.6.1 in [1] with two proposed solutions for implicit treatment of unknown simple types (UST) with arithmetic and comparison operators based on my earlier proposal in [2] and a subsequent simplification discussed at today's XPath TF call. The rewording should also refer to the basic conversion rules that are defined in [1] Section 2.1 as:. In addition, I assume that numeric and numeric types are well-defined terms referring to the set of types double, float, decimal and all their subtypes (derived by restriction). ******************************************** Proposal I: Rewrite to treat UST as double if operating with numeric types ******************************************** 2.5 Arithmetic Expressions <leave as is until "For example, a-b will be interpreted as a single token."/> An arithmetic expression is evaluated by applying the following rules that are based on the basic conversion rules, in order, until an error is raised or a value is computed: The required types of the operands of an arithmetic expression do not have required types. 1. If any operand is a sequence of length greater than one, a type exception is raised (applying the basic conversion rule to each argument). 2. If any operand is an empty sequence, the result is an empty sequence(applying the basic conversion rule to each argument).. (applying the basic conversion rule to each argument). 4. If any or both operands are an untyped simple value (such as character data in a schemaless document), the basic conversion rule is applied and the required type is xs:double. Thus an untyped simple value is cast to type xs:double.. This is an extension to the basic conversion rule.: <rest stays the same/> 2.6.1 Value Comparisons Value comparisons are intended for comparing single values. The result of a value comparison is defined by applying the following rules, based on the basic conversion rules, in order: 1. If either operand is an empty sequence, the result is an empty sequence. 2. If either operand is a sequence containing more than one item, an error is raised. 3. If either operand is a node, its typed value is extracted. If the typed value is an empty sequence, the result of the comparison is an empty sequence. If the typed value is a sequence containing more than one item, an error is raised. is of the other operand is numeric the required type becomes xs:double. - if the type of the other operand is unknown, then the required type for both becomes xs:string. - otherwise the type of the other operand becomes the required type. 5." ******************************************** Proposal II: Rewrite to treat UST as the other numeric type ******************************************** 2.5 Arithmetic Expressions Change Proposal I Rule 4 to: 4. If of the operands is an untyped simple value (such as character data in a schemaless document), the basic conversion rule is applied and the required type is set based on the type of the other operand: - the required type for both operands becomes xs:double if the type of the other operand is unknown - otherwise the required type becomes the type of the other operand. Thus an untyped simple value added to a float is cast to type xs:float. 2.6.1 Value Comparisons Change Proposal I Rule 4 to: of the other operand is unknown, then the required type for both becomes xs:string. - otherwise the type of the other operand becomes the required type. ******** Analysis ******** The advantage of proposal I is that it is closer to the known XPath behaviour (although as Peter pointed out not the same), it is simpler to explain and implement and allows expressions where the UST value is a double and an operation combines it with a type based on decimal that would lead to runtime errors in case II. Based on extensive discussions with my constituency, users and implementers alike, this seemed to be the preferred solution. The disadvantage is a slight loss of type precision on the result that can be regained by explicitly casting the result or operands to the desired type. Best regards Michael [1] [2] Decision by: xquery on 2002-03-27 ([link to member only information] ) XML Query WG has adopted a solution to Issues 259 and 91 as per Proposal 1 in Michael Rys' proposal. Decision by: xsl on 2002-03-28 ([link to member only information] ) Does expr instance of type define an expected type with type so that data() is implied explicitly on: let $e := <e xsi:type=?xsd:integer?/> return $e instanceof xsd:integer is that let $e := <e xsi:type=?xsd:integer?/> return data($e) instanceof xsd:integer and thus true or false? This issue is somewhat related to CAST (Issue 253), but since we perform a type test here, I would argue that we should not.? An alternative definition of data() on elements with known complex type: If $e is an element of an known (complex) type, then data($e) evaluates to the concatenation of $e's text nodes and has UnknownSimpleType. This definition is appropriate when explicit casts are necessary to convert UnknownSimpleType to other atomic types, i.e., when the basic conversion rules *DO NOT* implicitly convert UnknownSimpleType to other atomic types. The benefit of this alternative is that a user can always safely apply data() to any node and is guaranteed never to get an error. The the data() function is only defined on element and attributes with a simple type. The definition of data() on other kinds of nodes or on element and attributes with unknown type is still an open issue. The corresponding issue in the Formal Semantics document is Issue-108. Decision by: xpath-tf on 2002-04-11 ([link to member only information] ) xf:data(): decided that it should return the error object when applied to document, PI, comment and namespace nodes. This change should be reflected in the F&O, XPath and Data Model document.. Should we simplify the relationship between xsd:string and the anySimpleType'd data to have them both behave the same operationally by providing implicit coercions and being type compatible? Alternate, in some peoples view mutually exclusive, issue: Should we simplify the relationship between xsd:string and the anySimpleType'd data to have them both behave the same operationally by disallowing implicit coercions on anySimpleType and being type compatible? One difficulty in designing XQuery is that it must meet the needs of two quite different constituencies: Convenient: Quickly write queries to explore a large body of data. Works best with implicit coercions and dynamic typing. Reliable: Solidly engineer queries for web services. Works best with explicit coercions and static typing. We've already agreed to have two conformance levels, one with dynamic typing and one with static typing. Perhaps the dynamic typing level should have implicit coercions and the explicit typing level should have explicit coercions.. The current proposed text for XQuery element constructors precludes a "text node only" implementation. Since XSL should have semantics aligned with XQuery a decision needs to be made by the XSL WG as to if this restriction is acceptable to construction in XSLT. Should validation also check identity constraints? Note that valid identity constraints of partial documents does not imply validity of the document as a whole. The current document says that identity constraints are not checked. Does validation introduce new xsi:type attributes, or should xsi:type attributes introduced for validation be removed? Note: The XPath telcon suggested that we eliminate this issue and simply say that any attributes introduced for the purpose of validation are removed as part of the validate semantics. Should validate introduce xsi:type to reflect type annotations that are not explicitly stated using an xsi:type in the source document? The current draft introduces xsi:type to reflect inferred or dynamically computed types. Does //@xsi:type match an xsi:type attribute? Compare to xml:lang, xml:space, xmlns, which are not represented as attributes in the XML Information Set. Note, however, that xsi:type is represented as an attribute in the Infoset. Should we treat it like other special XML attributes in the Data Model? } We need a way to represent the type name of untyped character data. In XML Schema, there is no one type that corresponds to this - in strict mode, elements whose content is untyped character data will have the type 'anyType' and attributes whose content is untyped character data will have the type 'anySimpleType', but this interacts in somewhat complex ways with lax and skip validation. For now, we assume that character data may be associated with a SimpleType whose name is 'xs:unknownSimpleType'. This type does not currently exist in XML Schema, so we must coordinate with them on this issue. If Schema does not provide a single type to represent untyped character data, we will provide a keyword for it in the ItemType production. For our Formal Semantics, it would be very helpful to have a simple type to represent all numerics. For now, we are using the SimpleType name "xs:numeric". In XML Schema terms, this would be a union type. We must coordinate with XML Schema to see if they can support this. If not, we will provide a keyword for numerics in the ItemType production.). Is , a dyadic operator or (, , ,) a polyargument operator? The element construction rules seem to indicate the later, but the document is not clear. If , is a dyadic node-concatenation operation, then it would be more streamable than as an argument separator.) Grammar of path expressions has been reorganized to conform more closely to description in Formal Semantics. Material has been added on Named Typing, including detailed syntax for SequenceType declaration, explanation of static and dynamic type-checking, and new rules for type-matching in function calls. Explanatory material has been added on typed values, document order, and the error value. Some terminology has been changed for consistency with other documents; for example, "simple value" changed to "atomic value". Some changes have been made to rules for handling untyped data in arithmetic and comparison expressions. A more detailed specification is provided for the static and dynamic semantics of treat and assert. A new section has been added on validate expressions. More details have been provided on the semantics of element and attribute constructors, including their data model representations. A new section has been added on Input Functions, describing the input(), collection(), and document() functions. An Operator Mapping Table has been added (Appendix B.) Quantified expressions now permit multiple variable bindings. The semantics of sortby have changed: all ordering keys must now have the same type, and explicit control is provided over the placement of empty sort keys. The semantics of and, or, and quantified expressions have changed so that an implementation is not forced to evaluate all the operand expressions if it encounters an error or a conclusive result. Union, Intersect, and Except expressions now apply to nodes only, not to atomic values. The definitions of the precedes and follows operators have been made independent of the preceding and following axes, since these axes are not supported in XQuery. The operators == and !== have been changed to is and isnot. Quotes are now required around attribute values in element constructors, even if the value is computed by an enclosed expression. It has been clarified that the result of a dereference operator is a node list in document order without duplicates. It has been clarified that the default element namespace applies to types as well as to elements. Document had been completely rewritten during the joint work on XPath (see text in Intro). The following issues have been resolved: Should not( () ) == true or () or not3 function be defined? Do we really require for at the XPath expression level? Datatypes... XQuery suggests that XPath 2.0 should have a richer set of datatypes based on the built-in types of XML Schema and the notion of an ordered sequence. Do we need a Context Item to track the "current item" in a for itteration, and, if so, how should it work? How should "." work in relation to it? Does the context include a default namespace declaration? Do we need a datatype names binding in the context? How should qname-to-collation bindings be handled? Implied existential quantifiers Functions on Empty Sequences... What should happen if a function expecting one element is invoked on an empty sequence? Functions on Sequences... What should happen if a function expecting one element is invoked on a sequence of more than one element? Path iteration... How should the current node be passed to a function in a path-step? Should we use is and isnot instead of == and !==. Semantics of positional predicates in XPath Function call rules needed
http://www.w3.org/TR/2002/WD-xpath20-20020430/
CC-MAIN-2016-36
refinedweb
10,682
54.02
getsockopt() Get options associated with a socket Synopsis: #include <sys/types.h> #include <sys/socket.h> int getsockopt( int s, int level, int optname, void * optval, socklen_t * optlen ); Since: BlackBerry 10.0.0. See " Keepalive timing," below. SO_LINGER. SO_OOBINLINE. SO_RCVBUF and SO_SNDBUF. SO_RCVLOWAT. SO_RCVTIMEO. SO_REUSEADDR level: SOL_SOCKET Enables or disables the reuse of duplicate addresses and port bindings. Indicates that the rules used in validating addresses supplied in a bind() call allows/disallows local addresses to be reused. SO_REUSEPORT.. SO_SNDTIMEO. SO. For a few clients (such as windowing systems that send a stream of mouse events that receive no replies), this packetization may cause significant delays. Therefore, TCP provides a boolean option, TCP_NODELAY, to defeat this algorithm.: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
https://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/g/getsockopt.html
CC-MAIN-2018-43
refinedweb
136
52.36
Controlling SQL Text Indexing Services with SQL Managed Objects and VB.NET Some applications create whole databases and tables dynamically. Entity Diagramming tools such as ERwin generate databases. Application builders or customizers—like ACT—modify databases, and applications that permit customized data storage sometimes generate new tables or even whole databases. The challenge with dynamic generation is that your application is already running, and it is unlikely that you will be there to perform administrative tasks, such as enabling full text indexing. Full text indexing uses an indexing service and permits you to index text fields in SQL Server. The benefit is that you can use functions like FREETEXT in SQL Server queries to query one or more fields for fragments of text. The net effect is that full text indexing makes your database capable of performing Google-like searches. That is, with full text indexing you can let the user enter any text data and SQL Server can search multiple fields for that fragment with expressing a WHERE predicate for every combination. Instead of WHERE CustomerName LIKE 'somedata' OR ADDRESS CONTAINS 'somedata', and so forth, you write one predicate using the FREETEXT function and SQL Server searches all of the indexed columns for that text. Here is where full text searching is really useful. Many, many applications support search and find capabilities. Many of these applications typically have a label indicating the kind of data that will be used to build the filter and an input control of some sort. Based on the controls containing values a dynamic search is assembled with as many WHERE predicates as there are kinds of input data. All of these labels, controls, and dynamic assemblage of queries are time consuming. The no-brainer is that Google is a metaphor that everyone seems to get; hence its popularity. So, why not have one input field every time where the user can input any data and let the indexing service and full text indexing find the matches for you? Full text indexing makes this possible. My article from August 2005, FREETEXT Searches with SQL Server and ADO.NET, demonstrates how to configure indexing services manually and perform full text searches. (This article builds on that concept in a different way.) The aforementioned article walks you through FREETEXT searches and manually configuring indexing services. This article shows you how to enable full text indexing and FREETEXT searches dynamically. With SQL Server 2005, the SQL Management Objects (SMO) capabilities were added to SQL Server and the .NET framework. The result is that many of the things that one could do manually using SQL Server tools can now be accomplished programmatically using SMO and VB.NET. In this article, you will learn how to support full text searches on SQL Server Express 2005—it's already supported in non-Express versions—enable full text indexing with SMO, and write FREETEXT queries against indexed columns, all with .NET code. Preparing the Demo When you install Visual Studio 2005 or up, SQL Server Express 2005 is installed. Some of you may have access only to SQL Express and some more of you will be developing on your workstation with SQL Server Express. Unfortunately, the out-of-the-box install doesn't support full text indexing for SQL Server Express. Therefore, if you are using SQL Server Express and you want to try the full text indexing demo, read the next paragraph. Otherwise, if you are using SQL 2005 developer edition or above, you can skip the next paragraph. Downloading SQL Server Express 2005 with Advanced Services SP2 For SQL Express users, full text indexing is not supported. If you want to try the demo and be able to perform FREETEXT queries with SQL Server Express, download the SQL Server Express 2005 with Advanced services SP2 (Service Pack 2) update at. This service pack contains support for full text indexing. Reviewing Prerequisites for the Demo Obviously, you will need access to SQL Server. SQL Express 2005 works if you install Service Pack 2 with Advanced Services. The example program was written in Visual studio 2008, but SMO was released with .NET 2.0 and Visual Studio 2005, so those versions should work too. (Make sure to write me at pkimmel@softconcepts.com if the demo doesn't work in Visual Studio 2005.) Configuring Full Text Indexing Dynamically and Writing FREETEXT Queries The sample program assumes an existing database is present. The code configures full text indexing on an nvarchar column, populates the index, and performs a query using the FREETEXT function. In the sample program, a database that contains company and stock ticker symbols along with historical quotes is used. You can use the Northwind database, or any database, to complete the example. Simply substitute details such as the connection string, database name, table names, and indexes in the code to reflect actual elements in the database you are using. Adding References SQL Management Objects (SMO) uses elements of the framework defined in the Microsoft.SqlServer namespace. To try the demo, create a VB.NET application—a console application will do—and add the following additional references: - Microsoft.SqlServer.ConnectionInfo.dll - Microsoft.SqlServer.Smo.dll - Microsoft.SqlServer.SmoEnum.dll - Microsoft.SqlServer.SqlEnum.dll Having added the SMO assemblies, you will need these Imports statements to support the code as demonstrated in Listing 1. - Imports Microsoft.SqlServer.Management.Smo - Imports Microsoft.SqlServer.Management.Common - Imports System.Data - Imports System.Data.SqlClient If you miss an Imports staement, the compiler and Intellisense will help you fill in the blanks. Configuring Full Text Searches with SQL Management Objects The sample code is all in a single Main function in a Console application. This part describes the SMO code in the first half of the listing (see Listing 1) and the next section contains vanilla SQL code with a FREETEXT query. All of the code is shown in Listing 1. In the Main function in Listing 1, the code from Dim server to the line before the connectionString variable is the SMO code. Everything else is the SQL code. In Main, a Server object is created. In the example, I am using SQLExpress, as shown in the listing. Using the Server object, a database is requested via the Databases collection, passing in the name of the database. (If you are using Northwind, replace "StockHistory" with "Northwind". From the Database object, request the Table desired by invoking accessing the Database.Tables collection. The code defines a catalog name and checks to see whether the catalog already exists. If the catalog doesn't exist, the catalog is created by creating a new FullTextCatalog object passing in the DB object and the catalog name. This catalog is set as the default and the FullTextCatalog.Create method is called. Next, the Table object is used to determine whether a FullTextIndex exists. If not, a new FullTextIndex is created passing in the Table object. A FullTextIndexColumn object is created passing in the FullTextIndex object and the column-name to index. The column is added to the FullTextIndex.IndexedColumns property. The implication is that you can index multiple columns. (In practice, index every column that you may want to search on.) The SMO code is wrapped up enabling change tracking, providing a unique key—use the primary key column, which is required—and associate the catalog name with the index. Invoke FullTextIndex.Create and StartPopulation. Populating the index with an incremental population will permit you to start querying the full text indexes immediately, although on large databases some results may not be found until the index is substantially complete. If you elect to perform a full population, the database may be unavailable until indexing is complete. Page 1 of 2
http://www.developer.com/db/article.php/3749066
CC-MAIN-2017-34
refinedweb
1,289
55.34
KiXtart is a logon script processor and enhanced scripting language for computers running Windows NT or Windows 9x in a Windows networking environment. You can use the KiXtart free-format scripting language to display information, set environment variables, start programs, connect to network drives, read or edit the registry, change the current drive and directory, and much more. Although primarily used to create logon scripts, KiXtart can also be used as a general-purpose scripting tool for Windows administration. In part 1 of this series of Daily Drill Downs, I’ll introduce you to KiXtart, highlight some of the basics, and help you get started by providing a selection of working examples. How to get KiXtart KiXtart is provided by Microsoft free of charge but without official support. The language has been around for a long time; I’ve been using it for well over four years. Latest and greatest versions of KiXtart are available at: KiXtart logon scripts ScriptLogic CompTrends When you download KiXtart, you get a very comprehensive manual, amounting to some 111 pages. The manual describes in detail all the commands, macros, variables, expressions, and functions. The logon batch file First, I’d like to show you a batch file I use to begin the logon process: @ECHO OFF REM Check if on server REM =============================================== REM If on server, do not run logon script REM REM WIZMGR is an NT server application, therefore REM does not exist on NT Workstation (or 95) REM =============================================== if exist %windir%\system32\wizmgr.exe goto END :Workstation if exist c:\logon.ini del c:\logon.ini REM ================================================= REM Use local Kix32 if available to prevent "downloading" if dialin REM ================================================= If exist %windir%\Kix32.exe set KiXtart=Kix32 %0\..\ If Not exist %windir%\Kix32.exe set KiXtart=%0\..\KIX32 REM ================================================= REM ================================================= REM Run pre-logon patch %KiXtart%patch1\patch1.scr REM ================================================= REM ================================================= %KiXtart%logon.scr REM ================================================= REM ================================================= REM Run post-logon patch %KiXtart%patch11\patch11.scr REM ================================================= REM ================================================= REM If not dialing in, copy down KiXtart if new REM version (can't copy over when in use) REM If errorlevel 1 goto SkipCopy xcopy %0\..\KIX32.EXE %windir% /D /Q xcopy %0\..\Kx*.* %windir% /D /Q REM ================================================= :SkipCopy :END This batch file isn’t designed to run on a server. I prefer to make sure nothing happens to a server "behind the scenes" when someone logs on. KiXtart provides a method that allows you to check the operating system it’s running on, but it doesn’t differentiate between Windows NT Server and Workstation. After checking that the logon script isn’t running on a server, the batch file attempts to find the KiXtart application in the user's Windows directory. If it finds the application, the batch file sets a variable to the location. If not, the variable is set to KiXtart’s location on the logon server. This is handy if the user is dialing in, because it stops having to pull the KiXtart executable across the slow dial-up line to run it. I’ve included some sample code lines for calling patches. These patches can be KiXtart scripts or other batch files. Next, the batch file runs the KiXtart script Logon.scr, followed by any patches that should be run after the standard logon script. When you’re running a batch file during the logon process, the expression %0\..\ points to the Netlogon directory of the server that’s processing the logon—usually z:. Also, the system sets the environmental parameter %windir% to point to the directory where the Windows operating system is installed. This is standard for Windows NT and Windows 9x. Once the KiXtart processing has finished, the batch file will copy the KiXtart files to the user's Windows directory. The check for errorlevel 1 is used to prevent the copy from happening if the user is dialing in. The errorlevel is set to the exit status of KiXtart. This isn’t a definitive calling batch file. I’ve seen large and complicated ones where the KiXtart script is almost an afterthought, as well as shorter, simpler ones where the KiXtart application is left on the server and all the batch file does is call a KiXtart script. Although I tend to use the extension .scr for KiXtart script files, the currently recognized extension is .kix. However, you can use either one. Some useful macros KiXtart has its own built-in macros. They look like variables, but they extract the relevant values every time they’re referenced. So, if you’re going to use one of these macros more than a couple of times, it’s a good idea to use the macro once, put the result in a variable, and use that variable from then on. As I mentioned earlier, KiXtart provides a variable, @InWIN, which is set to 1 for Windows NT and 2 for Windows 9x. The drawback is that the variable doesn’t differentiate between NT Server and NT Workstation, and there’s no method for finding out what the x is in 9x. However, once you know whether it’s NT or 9x, you can then check the relevant registry key to get the true version. You can use KiXtart to assist in network optimization on a wide area network (WAN). The variable @IPADDRESS0 will give you the user's IP address, and the variable @LSERVER provides the name of the server handling the logon process. If you record these two values, you can determine whether users are being serviced by a local server or by a server over a slow link (and take the appropriate action if it’s the latter case). Other useful variables are: - @DATE: current date (YYYY/MM/DD) - @TIME: current time (HH:MM:SS) - @USERID: current user's Windows NT user ID - @WUSERID: current user's Windows user ID - @WKSTA: computer name - @FULLNAME: full name of user There are over 40 macros available in the latest version of KiXtart, so I won’t list them all here. Coping with slow connections The slowest connection you’re likely to encounter (barring networks with major problems) is via modem. In Windows 9x, following a successful dial-up connection the dialer changes a registry key. Here's the code: $Dialin_value=readvalue("HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\RemoteAccess","Remote Connection") if @ERROR > 0 ? "ERROR" endif if $Dialin_value=00000000 ? "No Connection" else ? "Connection Exists" endif I’ve introduced several new elements here, so let me break it down. Let’s start with the if....else....endif construct. It's pretty straightforward, but keep in mind that only the test for true or false can appear on the if line and that else is optional. The conditional operators are - < - > - = - <> - <= - >= You can combine these options by using AND or OR. Many of the commands and functions return true or false depending on whether they were successful, so you can write if command(paameter,parameter...) code if trueelse code if falseendif Next, let’s look at variables. All variables in KiXtart begin with $. Typing (deciding whether the variable is a string or a number) is automatic. Variables don’t have to be declared before they can be used. You can also implicitly declare them by assigning a value to them. Note that all variables declared in this way have a global scope. Arrays are the exception; you must declare arrays using the DIM statement. There’s no limit to the number of variables you can declare and, for all practical purposes, no limit on the number of elements you can have in an array. The third element I’ve introduced is the function readvalue. This function allows you to obtain information from the registry. It has two parameters: the key name and the value name. Finally, I’ve introduced @ERROR, which is set by most functions. If the function completed satisfactorily, @ERROR will be 0; otherwise, @ERROR will be set to a value that best represents the type of error encountered. The manual that comes with KiXtart lists all the error codes you’re likely to encounter. Communicating with the user Some logon scripts are written so that the user sees nothing and just sits there waiting for the thing to finish. Some are written so that the user is fully informed about what is going on. I prefer something in between: I like to display progress at certain relevant points so that, should the script fail for whatever reason, the user will have some idea of what was happening just before it failed. So, how do we communicate with the user? You may have noticed a little something in the example above that I omitted in the explanation that followed. Actually, I omitted it there so that I might include it in this section. If you’re not sure what I’m talking about, return to the example and look at what’s happening between if and else and between else and endif. Did you think that the ? at the beginning was a typo? Hands up everyone who thinks that the ? character is the equivalent of print (just like in BASIC)? That's what I used to think. Look at the following code: $line5="Finally, line 5" "This is line one...." "and this is line one" ? "but this is line two" ? "and this is line three" ? "and this is line four." ? $line5 This code will produce the following output: This is line one....and this is line one but this is line two and this is line three and this is line four. Finally, line 5 If you have a string on a line without any preceding command, that string is echoed to the console. Also, the ? character can appear anywhere on the line—it’s simply a quick way of printing a carriage-return, line-feed sequence. However, it’s pretty confusing if code is interspersed with lines consisting solely of variable and/or quoted strings. So, you can use ? at the beginning of anything you’re going to display; you use it as if it is the equivalent of print. Another way of displaying text is to use the display function. This function displays the contents of a file, which is useful for displaying set messages. However, you may find it a bit cumbersome to have to maintain the files outside the KiXtart script. A more complex but powerful function for displaying text messages is messagebox. As the name implies, this function is used to display a box containing a message in much the same way as most GUI applications. You have the ability to include one or more buttons, a title, and an icon. You can also obtain the value of the button clicked by the user. Here’s an example, which produces the box shown in Figure A: $x = MessageBox("The name of this computer does not comply with the standard naming convention for PCs. If not changed, this question will be asked next time." + chr(10)+chr(10)+"Shall I change it now?", "Logon Progress",36,15) Although the sample code produces the nice GUI box shown in Figure A, you’ll need a crib sheet to remind you how to arrive at the last two numbers. You’ll see what I mean when you look at the syntax of this command: MessageBox("message", "title", style, time-out) The elements message and title are self-explanatory; style, which is optional, is the sum of the values specifying the number and type of buttons to display, the icon style to use, the identity of the default button, and the modality. Let’s take a look at the values and their meaning: When adding numbers to create a final value for the argument type, use only one number from each group. If style is omitted, a default value of 0 is assumed. The time-out element is also optional. This specifies the number of seconds that pass before the message box closes if the user doesn’t press a button. If time-out is omitted, the message box won’t close until the user presses a button. Conclusion In this Daily Drill Down, I’ve given you some background on KiXtart, shown you a bit of code, and discussed a few of the common structures and commands. In future drill downs, I’ll discuss more structures and commands..
http://www.techrepublic.com/article/creating-logon-scripts-with-kixtart-part-1-background-and-common-structures/5031998/
CC-MAIN-2016-50
refinedweb
2,057
63.59
Aug 25, 2011 07:44 PM|araczynski2|LINK Ok, I think some people are after this functionality, but personally I am not in this case :) Built a VS2010 C# Web Project, Have a custom class for storing logged on user information ("User2"), with the [Serializable()] declaration. I then on a web form create a new object for User2 and then try to populate everything. After the object is created and populated, i put it in Session["ThisUser"] which i then try use on a page load of any response.redirect("..") to 'continue' with the same user. like: public partial class ExpenseForm : System.Web.UI.Page { User2 ThisUser = new User2(); protected void Page_Load(object sender, EventArgs e) { if (!(Page.IsPostBack)) { if (Session["ThisUser"] != null) { ThisUser = (User2)Session["ThisUser"]; if (!ThisUser.LOGINSECURED) { ThisUser.RETURNURL = HttpContext.Current.Request.Url.AbsoluteUri; Response.Redirect("Login.aspx"); } On two seperate (ie/firefox/chrome browsers), after loggin in properly, if i navigate to a different page it seems that the last logon will overwrite all session data in the first session/browsers, so on the first browser if i click somewhere else it will be with the second browser's user information (name/etc). The two browsers seems to show different Session.SessionID values however. This even happens if i log in on one computer and travel 50 miles to a different office. I've tried it with InProc and StateServer. At first i thought it was because i mistakenly put all the user variables inside the Global.asax, so that's why i created the seperate class to store the user data. but now Global.asax has no reference to any of the user2 variables nor does it create any instance of the object. its driving me nuts. What am I pulling a Simpsons on? All-Star 36250 Points MVP Aug 25, 2011 11:30 PM|HeartattacK|LINK Sessions are not shared across browsers. Most browsers let sessions be shared across tabs and possibly in different windows of the same browser. But different browsers will not share Session information. Just how the web works. If you want something different, you'll need to write your own (perhaps with the help of your database). Aug 26, 2011 12:51 PM|araczynski2|LINK I understand, that's what i'm saying, this behavior is what i'm SEEING, its not what i want. We're thinking it has something to do with the user2.cs object being serializable() and public? took out the serializable() part and changed the session mode to 'inproc' but still the same thing. Aug 26, 2011 01:42 PM|araczynski2|LINK ...now i'm starting to think its more likely that my user2.cs class isn't setup properly to serve up an empty instance of itself whenever its created... am i missing something in thinking that saying "User2 ThisUser = new User2();" will create a new EMPTY instance of the User2 object for each session? namespace Business4 { // [Serializable()] public class User2 { private static string _fp_first = string.Empty; public string FP_FIRST { get { return _fp_first; } set { _fp_first = value; } } .....} public String GetSignatureSelectorsData() { String processed = ""; using (SqlConnection conn = new SqlConnection(Global.connString)) { conn.Open(); using (SqlCommand cmd = new SqlCommand("GetSignatureSelectors", conn)) { cmd.CommandType = CommandType.StoredProcedure; try { SqlDataReader dr = cmd.ExecuteReader(); if (dr.HasRows) {.... All-Star 36250 Points MVP Aug 26, 2011 01:54 PM|HeartattacK|LINK I couldn't understand your code, but here's the deal: 1. You won't be able to share sessions across browsers. 2. What you can do is fetch the db entry on every request. That way, a change in one browser will be reflected in another. All-Star 26061 Points Aug 26, 2011 04:28 PM|markfitzme|LINK Are you defining all the fields as static? private static string _fp_first = string.Empty is not variable local to the object. If you are trying to access this, I would expect it to be the exact same for all users. The static keyword means it is not local to the object and the variable is actually available to all the versions of the class out there. if you update it for one user, all users immediately see the same value, until someone else changes it, then they all see that changed version. If you want a typical property that gets/sets a variable internal to the class just remove that static definition. All-Star 26061 Points Aug 26, 2011 04:47 PM|markfitzme|LINK Not a problem. It's often the simplest things, even one keyword, that provides the biggest headaches. Aug 26, 2011 05:35 PM|araczynski2|LINK we were just saying that this morning, it has to be something stupid/obvious that we're missing. but at least i learned something and might have a use for the mechanism the way i had it 'broken'. thank again. 8 replies Last post Aug 26, 2011 05:35 PM by araczynski2
https://forums.asp.net/t/1714467.aspx
CC-MAIN-2020-29
refinedweb
818
66.13
Ionic 5/Angular and InAppBrowser Webview: Create a Cross Platform Mobile App for Your Responsive Website Nowadays a great part of users are using mobile devices to browse the web so having a mobile ready website or app is crucial to your business. You might think that a responsive website is enough since you can reach mobile users just like using apps and that is correct but a mobile app has more features to offer, most importantly: - Apps can access all native device features (with users permission). - Apps are distributed and installable via app stores. In this tutorial we'll show you how you can turn your responsive website into a mobile app with a few steps then you can upload it to major app stores to reach millions of users, such as: - The Google store, - The Apple store, - The Microsoft store - Or the Amazon store. Here is the list of all supported platforms: Amazon Android BlackBerry 10 Browser Firefox OS iOS OS X Ubuntu Windows Windows Phone We are not going to build an app from scratch since the tutorial supposes you already have a responsive website so we are going to use Ionic 5 with Angular to create a webview (with Cordova InAppBrowser plugin ) or a web browser which loads your responsive website when the user launches the app. Tutorial requirements We are going to use the Ionic 5 framework which is the most popular hybrid framework for building cross platform apps for Android, iOS and Windows so you don't need to reinvent the wheel or use different tools and languages to target multiple platforms but we need to have some requirements before we can proceed with building the mobile app. Basically you need to have: - Node.js installed on your system. - Cordova and The Ionic CLI installed. - Java and Android SDK (If you want to build for Android) - A Mac system if you want to target iOS. - A Windows system and Visual Studio installed if you want to target Windows. You can install Node.js by going to their official website and download the installer compatible with your operating system. For Ubuntu users we have a tutorial which shows you how to install Node.js on Ubuntu. After installing Node.js, you can use NPM (Node Package Manager) to install both Cordova and the Ionic CLI via the terminal or command prompt by entering these commands: npm install -g cordova npm install -g ionic Note: You might need to add sudo before the two commands under MAC system. For installing Java and Android ,you just need to go to their official websites and grab installers for your OS . You can also follow this tutorial for installing Java under Ubuntu. Note: Please note that you just need to install Node.js, Cordova and Ionic to develop your app and you can use the browser to test it then you can install the other requirements when you need to build the actual platform specific executable or to test on a real device. You can also install an emulator and test on it if you don't have a real mobile device at hand when developing. Generating a New Ionic 5/Angular Project Now if you have both Node.js and Ionic CLI 5 installed,let's proceed by generating a new Ionic 5 project. Open your terminal under Linux/MAC or your command prompt under Windows and run the following command: ionic start myApp blank --type=angular You can name your project what you want. We are using myApp as name. blank is the name of the template the Ionic CLI will use to generate our project. It has only one page which is enough for us since we need just one to host our webview where our responsive website will be loaded. To make sure everything is alright serve your app using: cd myApp ionic serve Then visit with your browser. You should see your app up and running. Now we are going to add a target Cordova platform using: ionic platform add android | ios | windows Next we are going to add the InAppBrowser Cordova plugin which allows you to create a webview or an in app browser to host your responsive website. Then install Ionic Native plugin which wraps the InAppBrowser So go ahead and run: ionic plugin add cordova-plugin-inappbrowser npm install --save @ionic-native/in-app-browser Open the src/app/app.module.ts file and import the InAppBrowser plugin then add it to list of providers: /* .... */ import { InAppBrowser } from '@ionic-native/in-app-browser'; /* ... */ @NgModule({ declarations: [ MyApp, HomePage ], imports: [ BrowserModule, IonicModule.forRoot(MyApp) ], bootstrap: [IonicApp], entryComponents: [ MyApp, HomePage ], providers: [ StatusBar, SplashScreen, InAppBrowser, {provide: ErrorHandler, useClass: IonicErrorHandler} ] }) export class AppModule {} If you don't do this you are going to get an error message, when you start using the InAppBrowser plugin,which tells you: Error: Uncaught (in promise): Error: No provider for InAppBrowser! Open the src/pages/home/home.ts and add the following code: import { Component , OnInit } from '@angular/core'; import { NavController } from 'ionic-angular'; import { InAppBrowser } from '@ionic-native/in-app-browser'; /* 1 */ @Component({ selector: 'page-home', templateUrl: 'home.html' }) export class HomePage implements OnInit{ constructor(public navCtrl: NavController,private iab: InAppBrowser /* 2 */) {} ngOnInit(){ const browser = this.iab.create('','_self',{location:'no'}); /*3*/ } } 1 - We import the InAppBrowser Ionic native plugin from @ionic-native/in-app-browser 2 - We inject the InAppBrowser native wrapper via the class constructor 3 - We call the create method of InAppBrowser injected instance with our website URL with target as _self and {location : 'no'} to hide the in app browser location bar. Next open src/pages/home/home.html and delete everything then add: <ion-content padding> loading... </ion-content> You can test you your app in the browser just to make sure there are no syntax erros using the following command: ionic serve But you are not going to get the desired behavior because on the browser your website will be opened in a new popup. We want the website to be opened on the home page. To test your final app follow these steps. First enable the debug mode on your mobile device. Next attach your device to your computer with a USB cable. Next, open your terminal and run: ionic run android | ios | windows Depending on your device. For Android if you get the following error message: Error: Android SDK not found. Make sure that it is installed. If it is not at the default location, set the ANDROID_HOME environment variable. This means either: - You have not installed the Android SDK or - You have not properly configured environment variable which points to the Android SDK. So if you have installed the Android SDK and you still get the error you can just run this line before building your app: export ANDROID_HOME='/home/to/android/sdk' On Linux and MAC or its equivalent on Windows. Conclusion You can now wrap your existing responsive mobile website into a mobile app for major mobile platforms with minimum efforts using Ionic 5, Angular and Cordova InAppBrowser plugin to reach millions of worldwide users on app stores. You have also other options if you need more features,you can build a full fledged Ionic 5 app which consumes RSS feeds of your website. You may have noticed a bit of performance downgrade (especially on an old mobile device ). That's because apps built with Ionic 5 or any Cordova based framework are hybrid apps i.e not true 100% native mobile apps. If you want more performance you may want to check NativeScript which allows you to build truly native apps with native performance with the same features as Ionic 5 such as targeting cross platform devices with the same code base.
https://www.techiediaries.com/ionic-2-webview-inappbrowser/
CC-MAIN-2020-45
refinedweb
1,294
58.82
05 February 2009 01:47 [Source: ICIS news] SINGAPORE (ICIS news)--Japan Polypropylene (PP) will maintain a 70% production rate at all its facilities until the end of February due to weak demand, a company source said on Thursday. “We have been running our plants at this rate since early December due to poor demand,” the source said. As one of the largest PP producers in ?xml:namespace> The start-up of its new 300,000 tonne/year PP plant had been postponed due to weak demand. Mitsubishi Chemicals holds a 65% stake in Japan Polypropylene, while Chisso Petrochemical holds the remaining 35% stake..
http://www.icis.com/Articles/2009/02/05/9190289/japan+polypropylene+runs+plants+at+70+on+weak+demand.html
CC-MAIN-2013-20
refinedweb
104
68.5
#include <pluginRegistry.h> Base class for registering Hydra plugins using the plug mechanism. It is expected that each plugin has a pluginfo.json file that contains a list of types, where each type provides a list of base classes, displayName and priority. The priority is used to order plugins, with the plugin with the highest priority being at the front of the order. priority is a signed integer. In the event of two plugins having the same priority, the plugins are sorted alphabetically on the type name. The plugin sorted to the front is used as the default plugin, when not specified. Example: { "Types": { "CPPTypeName": { "bases": ["BaseTypeName"], "displayName": "Human Readable Name", "priority" : 0 } } } Definition at line 71 of file pluginRegistry.h. Constructs a Plugin Registry. pluginBaseType is the TfType of the class derived from HfPluginBase that provides the plugin API. Gives subclasses an opportunity to inspect plugInfo-based metadata at the time of discovery. Reimplemented in HdSceneIndexPluginRegistry. Increment the reference count on an existing plugin. Entry point for registering a types implementation. T is the plugin being registered. PluginBaseType is the HfPluginBase derived class that specifies the API (the same one the TfType is for in the constructor). Bases optionally specifies other classes that T is derived from. Definition at line 204 of file pluginRegistry.h. Returns the plugin from the given pluginId. The reference count on the plugin is automatically increased. Returns the description for the given plugin id. The plugin may not be loaded or been actually created yet. Returns an ordered list of all registered plugins. The plugins are ordered by priority then alphabetically Returns true if a plugin has been registered for the given id. The plugin may not be loaded or been actually created yet. Decrement the reference count on the plugin. If the reference count get to 0, the plugin is freed.
https://www.sidefx.com/docs/hdk/class_hf_plugin_registry.html
CC-MAIN-2022-33
refinedweb
308
51.65
go to bug id or search bugs for New/Additional Comment: Description: ------------ SplMinHeap have the same behavior than SplMaxHeap when inserting data. Top value of a SplMinHeap object is the max value instead of the min Test script: --------------- class MySimpleHeap extends SplMinHeap{ public function compare( $value1, $value2 ){ return ( $value1 - $value2 ); } } $obj = new MySimpleHeap(); $obj->insert( 8 ); $obj->insert( 0 ); $obj->insert( 4 ); foreach( $obj as $number ) { echo $number."\n"; } // Output display : 8, 4, 0 instead of 0, 4, 8 Add a Patch Add a Pull Request Automatic comment from SVN on behalf of cataphract Revision: Log: - Fixed bug #53588 (SplMinHeap bad sorting with custom compare function). This bug has been fixed in SVN. Snapshots of the sources are packaged every three hours; this change will be in the next snapshot. You can grab the snapshot at. Thank you for the report, and for helping us make PHP better. Reverted change and closing as bogus. Turns out the semantics of SplMinHeap::compare() and SplMaxHeap::compare() are different. See:
https://bugs.php.net/bug.php?id=53588&edit=1
CC-MAIN-2017-51
refinedweb
167
61.87
capture and save with 2 webcams C++ what do i need to add to my code in order to take the second picture as well ? right now it works only with one webcam, but i can see both on my screen. Thanks ! #include <opencv2/opencv.hpp> using namespace cv; int main() { //initialize and allocate memory to load the video stream from camera cv::VideoCapture camera0(2); cv::VideoCapture camera1(1); if( !camera0.isOpened() ) return 1; if( !camera1.isOpened() ) return 1; while(true) { //grab and retrieve each frames of the video sequentially cv::Mat3b frame0; camera0 >> frame0; cv::Mat3b frame1; camera1 >> frame1; cv::imshow("Video0", frame0); cv::imshow("Video1", frame1); //wait for 40 milliseconds int c = cvWaitKey(40); //exit the loop if user press "Esc" key (ASCII value of "Esc" is 27) if(27 == char(c)) break; } // Get the frame Mat save_img; camera0 >> save_img; if(save_img.empty()) { std::cerr << "Something is wrong with the webcam, could not get frame." << std::endl; } // Save the frame into a file imwrite("test1.jpg", save_img); // A JPG FILE IS BEING SAVED return 0; } index starts at 0. Have you got three webcams ? . It means that you don't use first webcam. try : and it is better to use cv::Mat frame0; instead of cv::Mat3b frame0; camera0 >> frame0; manage memory. and here save_img is empty and test1.jpg must be an empty file (or only a header) thanks for replying. im using 1,2 because i don t want my laptops webcam. i didnt really understand, i want to save one picture from each webcam, so what i should add to the code? thanks !
https://answers.opencv.org/question/148407/capture-and-save-with-2-webcams-c/
CC-MAIN-2020-50
refinedweb
269
72.16
From: Hartmut Kaiser (HartmutKaiser_at_[hidden]) Date: 2005-02-09 02:35:15 Gennadiy Rozental wrote: > > The Wave C++ preprocessor library review begins today February 7, > > 2005. > >? Note I do not comment on the > quality of the submission (I most probably is not qualified > enough to comment on that). After all this library/utility > exist already and available to public. IIRC it was discussed several times on this list, that - Boost should be more than a collection of libraries, it additionally should provide the C++ developer with general tools usable to improve there work. -. - Wave may be a helpful tool which could be used by developers sticking with older compilers (and bad preprocessors) but wanting to use the Boost.PP library in there code. >. Certainly I do have a comprehensive test suite here (otherwise I wouldn't have been able to make the library such compliant as it is), but this isn't a fully automated test suite yet and I currently can't give it away. But I agree with you: there should be such a test suite and I'd be willing to provide one given Wave will be accepted into Boost. To answer your question regarding how you may test whether the library does what it claims: just take your everyday code and pass it through Wave before compiling (just as you do with other compilers you trust). But perhaps others who have used Wave may want to comment on the issue of compliance as well. > 3. How are we supposed to comment on implementation? > Beyond a sheer volume of submission (more that 1 meg in > headers and sources), IMHO one needs to be an expert in both > Spirit and C++ preprocessor specification to make any > intelligent comments on what is written. I think you won't have to understand every bit in a library to give a judgement. Looking at the documentation and skimming over the code often gives a good impression about the quality of it. >. BTW: part of these headers aren't required to compile a program using Wave (especially the files related to the grammars). Part of them are required to compile the libraries only. So the question is, where to put these headers. I've put them all into one place (the boost/wave subdirectory) to comply with the Boost directory structure. But this is an issue I'm ready to discuss about. In the end it doesn't matter for the overall Boost size, where these files will end up: in the boost/wave or the libs/wave directory. If you look at the main header of the Wave library (it's the file cpp_context.hpp), which is the one containing the public interface, you'll see, that it exposes a really sparse public interface (as described in the documentation): - predefining macros, - managing include paths, - perhaps adjusting some additional parameters (as the mode to work in, i.e. C++ or C99, or the max allowed include nexting depth), - getting the current state the preprocessor in working in, and - getting the iterators to work on. Nothing more. The overall Wave codebase is heavily structured into namespaces (reflected by the directory structure) and the only classes in the boost::wave namespace are the context<> template and the iterators returned by the context<>. All the other classes reside in deeper namespaces (such as boost::wave::util) because they aren't part of the public interface. Hope this answers your questions. Regards Hartmut Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2005/02/80079.php
CC-MAIN-2021-04
refinedweb
599
60.75
#include <Pilot.h> Definition at line 2029 of file Pilot.h. List of all members. Definition at line 2031 of file Pilot.h. [virtual] Assumes the event is a completion event from the motion, throws a corresponding state node completion event. Reimplemented from MCNodeBase. Definition at line 2049 of file Pilot 2041 of file Pilot.h. May be overridden to cleanup when the behavior is shutting down. However events will automatically be unsubscribed, and by using addMotion(), motions will automatically be removed by stop(), so you may not need any cleanup. Definition at line 2054 of file Pilot.h. Adds the motion command to the motion manager, but stops it from running until the user has a chance to program it. Reimplemented from MCNode< HeadPointerMC, defHeadPointerNodeName, defHeadPointerNodeDesc, true >. Definition at line 2034 of file Pilot.h. Definition at line 2032 of file Pilot.h. Referenced by doStart().
http://tekkotsu.org/dox/classDualCoding_1_1Pilot_1_1SetOdometryMachine_1_1TurnHead.html
CC-MAIN-2018-47
refinedweb
147
52.87
Using the Input Subsystem, Part II March 1st, 2003 by Brad Hards in For some applications, it might be enough to know the device identity, because this would allow you to handle any special cases depending on what device is being used. However, it doesn't scale well; consider a case where you want to enable scroll wheel handling only if the device has a scroll wheel. You really don't want to have to list the vendor and product information for every mouse with a scroll wheel in your code. To avoid this problem, the event interface allows you to determine which features and capabilities are available for a particular device. The types of features supported by the event interface are: EV_KEY: absolute binary results, such as keys and buttons. EV_REL: relative results, such as the axes on a mouse. EV_ABS: absolute integer results, such as the axes on a joystick or for a tablet._FF_STATUS: device reporting of force-feedback effects back to the host. EV_PWR: power management events. These are only the types of features; a wide range of individual features can be found within each type. For example, the EV_REL feature type distinguishes between X, Y and Z axes and horizontal and vertical wheels. Similarly, the EV_KEY feature type includes literally hundreds of different keys and buttons. The capabilities or features of each device can be determined through the event interface, using the EVIOCGBIT ioctl. This function allows you to determine the types of features supported by any particular device, for example, whether it has keys, buttons or neither. It further allows you to determine the specific features that are supported, for example, which keys or buttons are present. The EVIOCGBIT ioctl takes four arguments. If we consider it as ioctl(fd, EVIOCGBIT(ev_type, max_bytes), bitfield), then the fd argument is an open file descriptor; ev_type is the type of features to return (with 0 as a special case, indicating the list of all feature types supported should be returned, rather than the list of particular features for that type); max_bytes shows the upper limit on how many bytes should be returned; and bitfield is a pointer to the memory area where the result should be copied. The return value is the number of bytes actually copied on success or a negative error code on failure. Let's look at a couple of examples of the EVIOCGBIT ioctl call. The first example, Listing 7, shows how to determine the types of features present. It determines how much memory is required for the bit array using evtype_bitmask, based on the EV_MAX definition in <linux/input.h>. The ioctl is then submitted, and the event layer fills in the bit array. We then test each bit in the array and show where the bit was set, which indicates the device does have at least one of this type of feature. All devices support the EV_SYN feature type in 2.5; the input core sets this bit. Listing 7. Determining Features with EVIOCGBIT When run, with a keyboard as the target, the example in Listing 7 produces: Supported event types: Event type 0x00 (Synchronization Events) Event type 0x01 (Keys or Buttons) Event type 0x11 (LEDs) Event type 0x14 (Repeat) With a mouse as the target, the example produces: Supported event types: Event type 0x00 (Synchronization Events) Event type 0x01 (Keys or Buttons) Event type 0x02 (Relative Axes) Having determined what capabilities a particular device has, you know what types of events it will produce and what types of events you can send. Retrieving events from a device requires a standard character device “read” function. Each time you read from the event device (e.g., /dev/input/event0), you will get a whole number of events, each consisting of a struct input_event. Listing 8. Checking for Busy Spots The example shown in Listing 8 does a busy loop on the open file descriptor, trying to read any events. It filters out any events that don't correspond to keys and then prints out the various fields in the input_event structure. Running this while typing on my keyboard produced: Event: time 1033621164.003838, type 1, code 37, value 1 Event: time 1033621164.027829, type 1, code 38, value 0 Event: time 1033621164.139813, type 1, code 38, value 1 Event: time 1033621164.147807, type 1, code 37, value 0 Event: time 1033621164.259790, type 1, code 38, value 0 Event: time 1033621164.283772, type 1, code 36, value 1 Event: time 1033621164.419761, type 1, code 36, value 0 Event: time 1033621164.691710, type 1, code 14, value 1 Event: time 1033621164.795691, type 1, code 14, value 0 You get one event per key press and another per key release. This read interface has all the normal characteristics of a character device, meaning you don't need to use a busy loop. You can simply wait until your program needs some input from the device and then perform the read call. In addition, if you are interested in the input from a number of devices, you can use the poll and select functions to wait on a number of open devices at the same time. Sending information to the device is a process similar to receiving it, except you use the standard write function instead of read. It is important to remember that the data used in the write call has to be a struct input_event. A simple example of writing data is shown in Listing 9. This example turns the Caps Lock LED on, waits 200 milliseconds and then turns the Caps Lock LED off. It then turns the Num Lock LED on, waits 200 milliseconds, and then turns the Num Lock LED off. The cycle then repeats (in an infinite busy loop), so you see alternate flashing of the two keyboard LEDs. Listing 9. Sample Data Write Function By now it should be fairly clear that you receive events only when something changes—a key is pressed or released, the mouse is moved and so on. For some applications, you need to be able to determine what the global state of the device is. For example, a program that manages keyboards may need to determine which LEDs are currently lit and which keys are currently depressed on the keyboard, even though some of the keys may have been depressed before the application started. The EVIOCGKEY ioctl is used to determine the global key and button state for a device. An example is shown in Listing 10. This ioctl is similar to the EVIOCGBIT(...,EV_KEY,...) function in some ways; instead of setting a bit in the bit array for each key or button that the device can send, EVIOCGKEY sets a bit in the bit array for each key or button that is depressed. Listing 10. Determining a Device's Global Key and Button State The EVIOCGLED and EVIOCGSND functions are analogous to EVIOCGKEY, except that they return which LEDs are currently lit and sounds that are currently turned on, respectively. An example of how you would use EVIOCGLED is shown in Listing 11. Again, each bit is interpreted in the same way as the bits in the bit array are filled in by EVIOCGBIT. Listing 11. Using EVIOCGLED You can determine the repeat rate settings for a keyboard using the EVIOCGREP ioctl. An example is shown in Listing 12, with two elements to the array. The first element specifies the delay before the keyboard starts repeating, and the second element specifies the delay between subsequent repeats. So if you hold down a key, you'll get one character straight away, a second character rep[0] milliseconds later, a third character rep[1] milliseconds after the second character and another character every rep[1] milliseconds thereafter, until you release the key. Listing 12. Checking the Repeat Rate Settings You also can set the key repeat rate using EVIOCSREP. This uses the same two-element array that you'd use to get the settings, as shown in Listing 13; it sets the initial delay to 2.5 seconds and the repeat rate to 1 per second. Listing 13. Setting the Repeat Rates Some input drivers support variable mappings between the keys held down (which are interpreted by the keyboard scan and reported as scancodes) and the events sent to the input layer. You can determine what key is associated with each scancode using the EVIOCGKEYCODE ioctl. An example is shown in Listing 14, which loops over the first 100 scancodes. The value of the scancode (input to the function) is the first element in the integer array, and the resulting input event key number (keycode) is the second element in the array. You can also modify the mapping, using the EVIOCSKEYCODE ioctl. An example is shown in Listing 15; this ioctl maps my M key to always produce a letter N. Be aware that keycode ioctl functions may not work on every keyboard—that USB keyboard is an example of a driver that does not support variable mappings. Listing 14. Looping over Scancodes The EVIOCGABS function also provides state information. Instead of filling in a bit array that represents the global state of boolean values, however, it provides a struct input_absinfo (see Listing 16) for one absolute axis. If you want the global state for a device, you have to call the function for each axis present on the device. An example is shown in Listing 17. The elements in the array are signed 32-bit quantities, and you can safely treat them as equivalent to int32_t. The first element shows the current value of the axis, the second and third elements show the current limits of the axis, the fourth element shows the size of the “flat” section (if any) of the response and the last element shows the size of the error that may be present. Listing 16. input_absinfo for an Absolute Axis Listing 17. Checking Globabl State by Axis to see, but how many users have figured how to get a joysti On May 19th, 2003 jago25_98 (not verified) says: :) Post new comment
http://www.linuxjournal.com/article/6429
crawl-002
refinedweb
1,686
67.99
C Program to Reverse a linked list in groups of given size Reverse a linked list in groups of given size C Program to Reverse a linked list in groups of given size. In this we will reverse the sub-nodes of the linked list according to the user given size, it is somehow same as reverse the nodes of the linked list which is not a big deal to reverse nodes of the linked list. For Example:- Input:- 31 -> 12 -> 4-> 24 -> 65 -> 76 ->7 -> 18; m = 2(given size by user) Output:- 12 -> 31 -> 24 -> 4 -> 76 -> 65 -> 18 -> 7; reverse of nodes as per user group size is 2. To learn more about this steps and code are given in C Programming Language. /> Steps required for Reverse a linked list in groups of given size:- - First of all we have to reverse the first sub nodes of the size m according to the user requirement. - While reversing the linked list keep observe the next node and previous node. - Now lets take the pointer to the next node be next and pointer to the previous node be prev. - Then take as head -> next = reverse (next, m). - Return prev. /> Structure for creating node in the singly linked list:- struct node { int data; struct node *next; }; To study more about linked list Click below:- C Program to Reverse a linked list in groups of given size #include <stdio.h> #include <stdlib.h> struct Node // Structure of node { int item; struct Node* next; }; struct Node *reverse (struct Node *head, int m) /* this function reverses the linked list in groups of size m and returns the pointer to the new head node*/ { struct Node* current = head; struct Node* next = NULL; struct Node* previous = NULL; void print_List(struct Node *node) //print function of the list { while (node != NULL) { printf("%d ",node->item); node = node->next; } } void insert(struct Node** head_ref, int new_data) //insert the data { struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); new_Node->item = new_Data; new_Node->next = (*head_ref); (*head_ref) = new_Node; } int counter = 0; while (current != NULL && counter < m) //reverse first m nodes of the linked list { next = current->next; current->next = previous; previous = current; current = next; counter++; } if (next != NULL) head->next = reverse(next,m); return previous; } int main() { struct Node* head = NULL; insert(&head, 91); insert(&head, 58); insert(&head, 17); insert(&head, 45); insert(&head, 53); insert(&head, 1); insert(&head, 8); insert(&head, 64); insert(&head, 15); insert(&head, 20); printf("The linked list is: \n"); print_List(head); head = reverse(head,4); printf("\nReverse a Linked List in groups of given size like m = 4 here: \n"); print_List(head); return(0); } Output:- The linked list is: 20 15 64 8 1 53 45 17 58 91 Reverse a Linked List in groups of given size like m = 4 here: 8 64 15 20 17 45 53 1 91 58 Login/Signup to comment
https://prepinsta.com/c-program/to-reverse-a-linked-list-in-groups-of-given-size/
CC-MAIN-2020-45
refinedweb
485
64.27
0 Hello there! Expora here again. I'm trying to get the hang of functions now and I made a simple program to calculate percent but I don't seem able to get it to work I can enter the 2 numbers but when i get the results is something like 0041123f. Any ideas? Here's the code: #include <iostream> //Percent Calculator int percent (int x, int y) { return (x/y)*100; } int main() { int x; int y; std::cout<<"Entrar dividendo: "; std::cin>> x; std::cin.ignore(); std::cout<<"Entrar divisor: "; std::cin>> y; std::cin.ignore(); std::cout<<"Su porciento es: "<< percent ; std::cin.get(); } Im thinking something where I defined the funtion? Well any input is apreciated. Thanks, Expora
https://www.daniweb.com/programming/software-development/threads/279978/trying-to-get-the-hang-of-functions
CC-MAIN-2016-50
refinedweb
122
66.84
Namespaced Javascript Template Self invoking anonymous function assigned to the yournamespacechoice global variable. Serves the effect of keeping all functions and variables private to this function. To expose a function or variable we must explictly return it at the bottom of the function. Remaps jQuery to $. var yournamespacechoice = (function ($) { var publicfunction; function privatefunction() { // function only available within parent function } publicfunction = function publicfunction() { // public function available outside of this funtion }; // Expose any functions that we need to access outside of this scope. Use yournamespacechoice.functionName() to call them. return { publicfunction: publicfunction }; }(window.$)); This type of function statement needs to exist before it is used. Shouldn’t you pass though window.jQuery? incase noConflict has been called earlier? Top marks Chris. I have using Glow as my JS library recently and have been struggling to write plugins without jQuery. Now when I map glow.dom.get to $ as the universal selector and use this namespace method I can make some truly powerful stuff! Cheers!
http://css-tricks.com/snippets/javascript/namespaced-javascript-template/
CC-MAIN-2013-48
refinedweb
162
60.11
More Videos Streaming is available in most browsers, and in the WWDC app. What's new in SwiftUI. Resources - Have a question? Ask with tag wwdc20-10041 - Search the forums for tag wwdc20-10041 - SwiftUI - Related Videos WWDC 2020 - App essentials in SwiftUI - Build complications in SwiftUI - Build document-based apps in SwiftUI - Build SwiftUI apps for tvOS - Build SwiftUI views for widgets - Data Essentials in SwiftUI - Introduction to SwiftUI - Meet WidgetKit - Optimize the interface of your Mac Catalyst app - SF Symbols 2 - Stacks, Grids, and Outlines in SwiftUI - The details of UI typography - What's new in Mac Catalyst - What's new in Swift - Widgets Code-along, part 1: The adventure begins - Widgets Code-along, part 2: Alternate timelines - Widgets Code-along, part 3: Advancing timelines - Download ♪ Voiceover: Hello, and welcome to WWDC. Matt Ricketson: My name is Matt Ricketson, and I work on the SwiftUI team. Later on, I'll be joined by my colleague Taylor. Last year we introduced SwiftUI, a powerful new way to build great user interfaces on all of Apple's platforms. We're incredibly excited to show you what's new in SwiftUI's second major release. As you'll soon find out, there are a ton of new features this year; much more than we can cover in just one talk, but we'll try to cover as much as we can. And along the way we'll let you know about other sessions that you can check out to learn more. First up, we'll introduce the new App and Widget APIs. We'll also talk about improvements to displaying Lists and Collections. We'll introduce new multi-platform APIs for toolbars and controls and also show you new kinds of visual effects for styling your apps. Finally, we'll discuss new ways for your SwiftUI apps to integrate with the rest of the system. But let's start with Apps and Widgets. For the first time, you can build an entire app using just SwiftUI instead of embedding your SwiftUI code within a UIKit, AppKit, or WatchKit app. Let's take a look. What you see here is a complete SwiftUI app. Just a simple Hello World! example. That's right: this is a 100 percent functioning app. You can build and run this code. In fact, it's so concise that you can fit the entire app into just 140 characters. But don't let this deceive you. SwiftUI packs a ton of intelligent, automatic, but also customizable behavior into a simple and flexible API for declarative apps. Here I've written an app for keeping track of the books I'm currently reading in my book club. At the bottom, I've written a custom view to represent my app's main user interface, and at the top, I'm using that view as the content of my app's main window. The first thing to notice here is how similar these two declarations are. We designed SwiftUI's new App API to follow the same declarative state-driven patterns you're already used to in your view code. In both cases you define a struct conforming to a protocol. You can declare data dependencies using properties, and that data is used within the body property, which for both apps and views, defines their declarative user interface content. However, you may notice one key difference, which is the return type of the app's body property. The body of an app returns a Scene, a new concept in SwiftUI that represents pieces of an app's user interface that can be independently displayed by the platform. We've prepared a whole talk that goes into more depth on what Scenes are and how they relate to apps and views. For now, I just want to focus on the scene we're using in this app called WindowGroup. That's because WindowGroup is a powerful example of how scenes in SwiftUI can provide intelligent, multi-platform functionality out of the box. In our iOS app, WindowGroup is creating and managing a single full-screen window for our application. But the same code can also run on watchOS, also managing a single full-screen window. Of course our watchOS app looks different than our iOS app but the core app structure is the same on both platforms, allowing them to share a single app declaration. In fact, my app will also work on tvOS and on the iPad too. And since iPadOS supports multiwindow apps, we get some additional functionality for free; like being able to create multiple instances of the app that can appear side-by-side. This also extends to macOS which also supports multiple windows. I can create new windows using the standard command-N shortcut and gather them up into a single tabbed window. SwiftUI will even automatically add a New Window menu command into my main menu. And all of this is made possible by this simple app declaration using the new WindowGroup API to define my interface. SwiftUI supports other types of scenes as well, which can be composed together like views to build more complex apps. Like the new Settings scene available on macOS for adding a Preferences window to your Mac app. The Settings scene will automatically set up the standard Preferences command in the app menu and also give the window the correct style treatment. SwiftUI's Scene APIs also support document-based apps, like this app that I built for drawing vector shapes. New this year is the DocumentGroup scene type, which automatically manages opening, editing, and saving document-based scenes supported on iOS, iPadOS, and MacOS. On iOS and iPadOS, DocumentGroup will automatically present a document browser if no other main interface is provided. And on the Mac, DocumentGroup will open a different window for each new document and also automatically add commands to the main menu for common document actions. Speaking of menu commands, SwiftUI lets you add additional commands as well using the new .commands modifier. For example, here I've added a custom shape menu for adding new shapes to the canvas. macOS will automatically add custom menus in the correct section of the main menu and will show their keyboard shortcuts, which we assigned using the new .keyboardShortcut view modifier. The .commands API has a lot more to offer than what we've shown here, such as being able to target commands based on user focus. It's really fun to work with. You can check out our reference documentation to learn more. There's a lot more to say about Apps and Scenes, and we've prepared a few other talks to help you dig deeper into these new APIs. App Essentials in SwiftUI explains how Views, Scenes, and Apps all work together in more depth and Document-Based Apps in SwiftUI dives deep into how to open and manage documents in your app. To help you build these new apps, we've also updated the new project experience in Xcode by adding new multiplatform templates specifically for SwiftUI apps. These new templates are optimized for multiplatform code automatically setting up groups for shared code as well as platform-specific components and assets. Another part of the project experience we're extending is how you configure your app's launch screen. New this year is the Launch Screen info .plist key. This allows you to declare various combinations of standard launch screen components such as default images, background colors, and empty top and bottom bars like I've configured here. You may already be using a Storyboard for your launch screen, which still works great, and there's no reason to switch. But for new SwiftUI projects that otherwise don't use Storyboards, launch screen configurations are a simple alternative. Now let's talk about Widgets, an exciting new feature on iOS, iPadOS, and macOS. Widgets are built exclusively with SwiftUI. You build Widgets just like Apps and Views using a custom struct conforming to the new Widget protocol. You can make many different types of Widgets like this one that periodically recommends a new album for me to listen to. Widgets can also be configured with other kinds of data such as Siri Intents. There's a lot to cover when it comes to building widgets, and we have several talks to help you get started. I'd recommend watching Build SwiftUI Views for Widgets to learn more. And finally, you can now use SwiftUI to build custom complications for Apple Watch. You can build a full color complication like this weekly coffee chart I made and also customize how it looks within a tinted watch face, like this cool blue tint that I like to use. To learn more check out Build Complications in SwiftUI. Or if you're new to building complications, I'd recommend starting with Creating Complications for Apple Watch. Next let's talk about improvements to displaying lists and collections. Lists are a vital component of many apps often representing the primary interface that users interact with. In this release, Lists are gaining some great new features. I'm especially excited about the new support for outlines. Regular lists enable concise declarations of dynamic, data-driven content. By providing a .children key path to its initializer, a List can now build out recursive outlines of content. By default, this shows up using the expected system standard styling on macOS and on iOS, and iPadOS. We hope that easy-to-use outlines can help reduce the need for disruptive push and pop navigation patterns within content-focused apps. Along with lists and outlines, it's also common to show collections of content in other kinds of scrollable layouts such as grids. This year SwiftUI is adding support for lazy loading grid layouts, which can be composed with ScrollViews to create smooth scrolling grids of content. Grids are powerful layouts that support a variety of different configurations, such as adapting the number of columns to fit the available space, like we see here in both landscape and portrait. Or forcing a fixed number of columns that can each have their own sizing parameters, like this example that sticks with four columns in every orientation. And of course, SwiftUI also supports horizontally scrolling grids. We're also exposing lazy-loading versions of the existing vertical and horizontal stack layouts which are great for building custom scrollable layouts, like this asymmetric gallery of images. Let's take a closer look. Here we're using a lazy vertical stack containing all of our gallery content. We're also using the new view builder support for switch statements allowing us to easily alternate between different image layouts within the stack, such as the single large image shown at the top, the asymmetric groups of three images, and the shorter rows of smaller images. Together composed with a lazy-loading, vertically-scrolling stack, they form a seamless gallery. Lists and collections are powerful features of SwiftUI, and we've only scratched the surface of what they're capable of in this talk. To learn more, you should really check out check out our talk on stacks, grids, and outlines. And now to talk about toolbars and controls, I'll hand things over to Taylor. Taylor Kelly: Thank you, Matt. It is so cool to see how easy it is to have our app's model come to life using SwiftUI with things like the new Document group and new collection views. Now let's jump in to the powerful toolbar support in SwiftUI and new ways to customize controls. Toolbars and apps across our platforms have some amazing new updates. From their beautiful new look in macOS Big Sur, to the updated iPad system experience, to the primary actions on watchOS. And this year, SwiftUI has a new API for constructing all of these using the new .toolbar modifier. Toolbar items consist of the same views you use throughout the rest of SwiftUI, in this case: a button. They will be placed in idiomatic locations by default but can be explicitly customized through the use of toolbar items. In this case, the primary action is the default placement on watchOS, but there are other placements as well. For instance confirmation and cancellation modal actions. These are examples of semantic placements, where you're describing to SwiftUI the role that these toolbar items have, and SwiftUI automatically figures out the right spot. Another example is the principal placement, to give an item prominence in your app as you see here on iPad... and on macOS. Toolbar items can have positional placements where you want to have that extra level of design control over where your items are placed. Particularly in narrow size classes, it's common to have items in bottom toolbars, and the literal .bottomBar placement allows you to explicitly specify that. You've probably noticed in a few of these examples the use of a new Label view SwiftUI. Let's take a closer look at that. This is a combined representation of a title and an icon that can be used to label UI elements. Here we have a string used as a localization key for its title and the name of a system image or SF Symbol. And this year not only are symbols available on macOS, but there are hundreds of new ones available for your apps to use. The SF Symbols 2.0 talk goes into more detail on all the new enhancements to symbols this year. This construction of label is actually a convenience for its full form, which is using any view for that title and icon. And its power comes from the semantics it provides for that title and icon, so they can be treated appropriately based on where they're used. So returning to our toolbar example, in the context of a .toolbar, by default, it'll just be icon visually presented as the buttons label and the title used for accessibility purposes. This behavior extends from toolbars to context menus to lists. Now this List contains multiple rows of Labels. The titles are perfectly aligned regardless of image size, and the power of Labels really shines when using different dynamic type sizes. This is showing the layout for the default large size category, and as that changes to extraExtraLarge, both the icon and title update automatically, including nicely reflowing the text and growing the list rows. An even further specialization happens at the larger accessibility sizes. At those, the labels have updated text wrapping around the icon to maximize the amount of visible text. Now with contexts like toolbars having clean, icon-only styles of labelling elements, providing additional help or context for those is more important than ever. With the new .help modifier, you can attach the descriptions of what effect a control will have, and that will manifest as tooltips on macOS. What's really cool is that this modifier is available on all platforms as it also provides an accessibility hint to provide an even better VoiceOver experience for your app everywhere. Here we can see a similar experience for our app on the phone for that same toolbar item. VoiceOver: Progress. Button. Record new progress entry. Taylor: It is so cool how our SwiftUI declarations can naturally improve the experience of our app for everyone. Now another new way of bringing more flexibility and power to how people interact with your controls is using the .keyboardShortcut modifier. These are most often used for Scene commands as it's critical for allowing those commands to be accessible via a keyboard shortcut an iPad and on macOS through the main menu, like Matt showed earlier. However keyboard shortcuts can also be used for other controls that are shown on screen, such as creating Cancel and default action buttons that have keyboard shortcuts of Escape and Return keys. From keyboards, to TV remotes, to the watchOS Digital Crown, focus drives how these indirect inputs are routed in your app. And using the new default focus support, your app can now control where focus starts on screen and how that default might change alongside your app state. The SwiftUI for tvOS session goes into more detail on using that new support as well as other tips for crafting a great tvOS app using SwiftUI. Last but not least, there are a couple of new controls that you can now use throughout your app. First are ProgressViews. These can be used to display determinant and indeterminate progress over time. They're both linear and circular style ProgressViews, the latter enabling everyone's favorite spinning style as a display of indeterminate progress. A similar new control are Gauges. Gauges are used to indicate the level of a value relative to some overall capacity. Here I have a circular watchOS gauge for tracking the acidity level of my garden soil. Gauges have additional optional customizations. Tomatoes are finicky enough to where I'd really like to see the exact pH level at a glance, so I can add a current value label to allow that to be displayed. Gauge can also have minimum and maximum value labels. In some cases those might be image icons, but here, I'm just going to display those pH levels as text. Now this code snippet also highlights the new multiple trailing closure syntax in Swift. It allowed the expression of our gauge to grow naturally as it gained additional complexity. It is really nice having a new, expressive way of creating toolbars across all of the platforms my apps support, plus these new means of really fine-tuning the behavior of controls both in and out of toolbars. Next up, let's take a look at new ways of crafting immersive and fun experiences using SwiftUI. macOS Big Sur has a gorgeous revamp to Notification Center and the new Control Center in the Menu Bar, both built using SwiftUI. Control Center features these smooth animations in and out of its different modules, using a new feature in SwiftUI that you can use in your own apps. Here I built a little prototype of UI to gather up my favorite albums. It consists of a scrolling grid of albums and the row of the selected ones. Now on selection, rather the album's just popping into that row, I'd really like them to fluidly transition from the grid. And using matchedGeometryEffect, it's really easy. I can apply the .matchedGeometryEffect modifier to the albums in both the grid and the selected album row using the album's identifier as the identifier to connect the two views, as well as the namespace that those identifiers are relative to. In this case, it's the namespace associated with the containing view. And that's really all it takes to create this effect. As an album is removed from one section and inserted to the other, SwiftUI will automatically interpolate their frames as a seamless transition. Another fantastic new tool is ContainerRelativeShape. This is a new shape type that will take on a similar path of the nearest containing shape. We can see the effect here in a widget for our favorite album. The clip shape on our album artwork automatically took on a concentric corner radius relative to the shape of the widget, and so fits perfectly within it. We can really get a feel for how cool this is by changing that padding, which effectively changes the offset to that outer container shape and thus the clipping of our view using container relative shape reacts beautifully, automatically maintaining that concentricity based on its offset. There are a few other enhancements to refine the experience of text-related elements as well. Custom fonts will automatically scale with dynamic type changes. Further, now that images can be embedded within text, they'll act as a unified part of that text, including reacting to dynamic type. And for any custom, non-text metrics such as for layout, there's a new ScaledMetric property wrapper that automatically scales some base value against the current dynamic type size. Altogether, these make it so easy to create responsive, custom layouts that react well in these larger accessibility sizes. There'll be another talk that goes into detail on this as well as other advanced font and typographic features that can be used to really make your app shine. Now these were a few of the new tools for building creative and reactive custom views, but the enhancements to styling your app don't stop there. Even when using system controls, you can customize them to look and feel at home on your app and make your app stand out from the rest by using a custom accent color. New this year is the ability to customize that accent color on macOS, and new support for customizing that accent color directly in the asset catalog in Xcode 12. This lets you easily specify that color for all of the platforms that your app supports. Now this is great for applying a broad theme color across your app, but there are also cases where you might want to specifically customize the tint of a single control. Now by default, Sidebar icons on iPadOS and macOS follow the app accent color. With a new .listItemTint modifier, you can customize the tint of those icons per item or even for an entire section. The same effect applies to macOS sidebars where these modifiers also react appropriately for changes to the system accent color. This same modifier also applies to watchOS where it's used to tint the standard platter background. And we've brought this tinting support to other controls as well. Using new style customizations, controls like buttons and toggles can now be explicitly tinted. Here at the switch, fill is customized to follow the overall themed accent color rather than the default green. Now all of these new views and interactions enable an even more polished and fun experiences within your app. And last but certainly not least, let's take a look at new ways your app can integrate and take advantage of functionality and services provided by the system. This year SwiftUI has a first-class API for opening URLs, available on all platforms. One form of this is in a new Link view, which takes the URL to open and the label of the link. It does what you'd expect, creating a visual element with that label and opening that URL with the default web browser. But in addition, it can also open universal links directly into other apps, in this case, News. Links also even work within Widgets where they can even link directly back into content within your main app. Now in the context of apps, there are cases where URLs need to be programmatically opened. For these advanced cases, there's also an .openURL action in the environment, which can be called with the URL to open in an optional completion handler. Because it's in the context of a specific view, SwiftUI automatically opens that URL relative to its containing window. In an update to iPadOS 13, SwiftUI gained support for enabling your app to both the drag to other apps and receive drops from those apps, making your iPad app even more powerful and integrated. And in iOS 14 and macOS Big Sur, this API is built on top of a new framework that enables stronger typed identifiers for the contents being dragged using the new UniformTypeIdentifiers framework. This has been adopted throughout SwiftUI, allowing you to take advantage of its features throughout your app. From extending it with your app's custom exported or imported types to introspecting type, for instance getting us human presentable description or validating its conformance. The Document-Based Apps in SwiftUI talk has more details such as the differences between imported and exported types. And there's also some great documentation available on Apple's web site. One last example of enabling your app to integrate with other services is the SignInWithApple button. This is again a first-class SwiftUI API provided by Authentication Services and available on every platform. What's really cool is that simply by importing AuthenticationServices and SwiftUI together, you get these new APIs. There is no new import or framework needed. And this is just one example of the many Apple frameworks that are now providing SwiftUI views and modifiers. From video players to maps to App Clip overlays, it's even easier to bring these advanced features into your SwiftUI app. Many of these are fully multiplatform, including natively on watchOS, meaning when you learn how to use these frameworks for one platform, you can apply that anywhere. And that was a quick summary of some of the new ways your apps can integrate and take advantage of the various system features now available in SwiftUI. We've run through a lot of new features and APIs, and like Matt mentioned at the beginning, there's just so much more that we didn't have time to talk about. But as one last call-out: throughout the talk, we came across a few examples where our apps' SwiftUI code was made even better from improvements to language itself. This year's What's New in Swift goes into more details on all of the awesome changes in Swift. It has more examples of syntax refinements, like builder inference and support for switch and if-let inside of builders. The compiler now has even better diagnostics that helps more quickly pinpoint build errors in your code and finally improve performance such as reductions of code size for your SwiftUI apps and faster code completion. These are the types of things that make using SwiftUI that much more enjoyable. We are so excited to share all of this with you this year. But lastly, thank you! Thank you for the excitement and passion we've seen from the community. Thank you for the reports on feedback assistant, the commentary on social media, the discourse on the forums, the many days of tutorials, and all of the amazing prototypes and explorations people have built. We're just blown away by the excitement we've seen and are really looking forward to what's yet to come. ♪ Looking for something specific? Enter a topic above and jump straight to the good stuff. An error occurred when submitting your query. Please check your Internet connection and try again.
https://developer.apple.com/videos/play/wwdc2020/10041/
CC-MAIN-2020-34
refinedweb
4,444
61.46
#include <stdio.h> int main() { int cookie; char buf[80]; printf("buf: %08x cookie: %08x\n", &buf, &cookie); gets(buf); if (cookie == 0x01020005) printf("you win!\n"); } Not much is new here. We exploit this the same was we did the first two except that we have a null character (ctrl @). I want to point out one thing that I didn't mention on my previous posts. The address of cookie and buf are printed out so we don't really need to "guess" where they are on the stack. I ignored this before, because in real programs, the address values are rarely printed out.
https://blog.eitanadler.com/2010/12/
CC-MAIN-2019-09
refinedweb
105
80.62
#include <wx/tipdlg.h> This is the class used together with wxShowTip() function. It must implement wxTipProvider::GetTip function and return the current tip from it (different tip each time it is called). You will never use this class yourself, but you need it to show startup tips with wxShowTip. Also, if you want to get the tips text from elsewhere than a simple text file, you will want to derive a new class from wxTipProvider and use it instead of the one returned by wxCreateFileTipProvider(). Constructor. Returns the index of the current tip (i.e. the one which would be returned by GetTip()). The program usually remembers the value returned by this function after calling wxShowTip(). Note that it is not the same as the value which was passed to wxShowTip + 1 because the user might have pressed the "Next" button in the tip dialog. Return the text of the current tip and pass to the next one. This function is pure virtual, it should be implemented in the derived classes. Returns a modified tip. This function will be called immediately after read, and before being check whether it is a comment, an empty string or a string to translate. You can optionally override this in your custom user-derived class to optionally to modify the tip as soon as it is read. You can return any modification to the string. If you return wxEmptyString, then this tip is skipped, and the next one is read.
https://docs.wxwidgets.org/3.0/classwx_tip_provider.html
CC-MAIN-2018-51
refinedweb
247
72.05
# .NET: Tools for working with multi-threading and asynchrony – Part 1 *I have originally posted this article in [CodingSight](https://codingsight.com/net-tools-for-working-with-multi-threading-and-asynchrony-part-1/) blog* *The second part of the article is available [here](https://habr.com/post/461471/)* The need to do things in an asynchronous way – that is, dividing big tasks between multiple working units – was present long before the appearance of computers. However, when they did appear, this need became even more obvious. It is now 2019, and I’m writing this article on a laptop powered by an 8-core Intel Core CPU which, in addition to this, is simultaneously working on hundreds of processes, with the number of threads being even larger. Next to me, there lies a slightly outdated smartphone which I bought a couple of years ago – and it also houses an 8-core processor. Specialized web resources contain a wide variety of articles praising this year’s flagship smartphones equipped with 16-core CPUs. For less then $20 per hour, MS Azure can give you access to a 128-core virtual machine with 2 TB RAM. But, unfortunately, you cannot get the most out of this power unless you know how to control interaction between threads. #### Contents * [Terminology](#Terminology) * [A Metaphor](#Metaphor) * [.NET Tools](#NetTools) + [Starting a Thread](#StartingAThread) + [Viewing and Debugging Threads](#ViewingAndDebuggingThreads) + [Task Parallel Library](#TaskParallelLibrary) + [Stopping Threads](#StoppingThreads) + [Turning a Legacy API Into a Task-Based One by Using FromAsync](#FromAsync) + [Turning a Legacy API Into a Task-Based One by Using TaskCompletionSource](#TaskCompletionSource) + [TaskCompletionSource Tips & Tricks](#TaskCompletionSourceTips) + [ValueTask: Why and How](#ValueTask) + [TaskScheduler: Controlling Task Execution Strategies](#TaskScheduler) + [PLinq and the Parallel Class](#PLinq) * [Summary](#Summary) ### Terminology **Process** – an OS object which represents an isolated address space containing threads. **Thread** – an OS object which represents the smallest execution unit. Threads are constituent parts of processes, they divide memory and other resources between each other in the scope of a process. **Multitasking** – an OS feature which represents the capability of executing multiple processes simultaneously. **Multi-core** – a CPU feature which represents the ability to use multiple cores for data processing **Multiprocessing** – the feature of a computer which represents the capability to physically work with multiple CPUs. **Multi-threading** – the feature of a process which represents the capability of dividing and spreading the data processing between multiple threads. **Parallelism** – simultaneous physical execution of multiple actions in a unit of time **Asynchrony** – executing an operation without waiting for it to be fully processed, leaving the calculation of the result for later time. ### A Metaphor Not all definitions are effective and some of them require elaboration, so let me provide a cooking metaphor for the terminology I just introduced. Making breakfast represents a **process** in this metaphor. When making breakfast in the morning, I(**CPU**) go to the kitchen(**Computer**). I have two hands(**Cores**). On the kitchen, there is an assortment of devices(**IO**): stove, kettle, toaster, fridge. I turn on the stove, put a frying pan on it and pour some vegetable oil in it. Without waiting for the oil to heat (**asynchronously, Non-Blocking-IO-Wait**), I get some eggs from the fridge, crack them over a bowl and then whip them with one hand(**Thread#1**). Meanwhile, the second hand(Thread#2) is holding the bowl in place (**Shared Resource**). I would like to turn on the kettle, but I don’t have enough free hands at the moment (**Thread Starvation**). While I was whipping the eggs, the frying pan got hot enough (Result processing), so I pour the whipped eggs into it. I reach over to the kettle, turn it on and look at the water being boiled (**Blocking-IO-Wait**) – but I could have used this time to wash the bowl. I only used 2 hands while making the omelet (because I don’t have more), but there were 3 simultaneous operations being executed: whipping the eggs, holding the bowl, heating the frying pan. CPU is the fastest part of the computer and IO is the part which requires waiting the most often, so it is quite effective to load the CPU with some work while it’s waiting for the data from IO. To extend the metaphor: * If I was also trying to change my clothes while making the breakfast, then I would have been **multitasking**. Computers are way better at this than humans are. * A kitchen with multiple cooks – for example, in a restaurant – is a **multi-core** computer. * A mall food court with many restaurants would represent a **data center**. ### .NET Tools .NET is really good when it comes to working with threads – as well as at many other things. With each new version, it provides more tools for working with threads and new OS thread abstraction layers. When working with abstractions, the developers working with the framework are using an approach that allows them to go one or more layers down while using high-level abstractions. In most cases, there is no real need to do this (and doing this may introduce a possibility of shooting yourself in the foot), but sometimes this may be the only way to resolve an issue that cannot be solved on the current abstraction level. When I said tools earlier, I meant both program interfaces (API) provided by the framework or third-party packages and full-fledged software solutions that simplify the process of searching for issues related to multi-threaded code. #### Starting a Thread The Thread class is the most basic .NET class for working with threads. Its constructor accepts one of these two delegates: * ThreadStart – no parameters * ParametrizedThreadStart – one object-type parameter. The delegate will be executed in a newly-created thread after calling the Start method. If the ParametrizedThreadStart delegate was passed to the constructor, then an object should be passed to the Start method. This process is needed to pass any local information to the thread. I should point out that it takes a lot of resources to create a thread and the thread itself is a heavy object – at least because it requires interaction with the OS API and 1MB of memory is allocated to the stack. ``` new Thread(...).Start(...); ``` The ThreadPool class represents the concept of a pool. In .NET, the thread pool is a piece of engineering art and the Microsoft developers invested much effort to make it work optimally in all sorts of scenarios. **The general concept:** *When started, the app creates a few threads in the background, allowing to access them when needed. If threads are used frequently and in great numbers, the pool is expanded to satisfy the needs of the calling code. If the pool doesn’t have enough free threads at the right time, it will either wait for one of the active threads to become unoccupied or create a new one. Based on this, it follows that the thread pool is perfect for short actions and does not work that well for processes that work as services for the whole duration of the application’s operation.* The QueueUserWorkItem method allows to use threads from the pool. This method takes the *WaitCallback*-type delegate. Its signature coincides with the signature of ParametrizedThreadStart, and the parameter that is passed to it serves the same role. ``` ThreadPool.QueueUserWorkItem(...); ``` The less-commonly-known RegisterWaitForSingleObject thread pool method is used to organize non-blocking IO operations. The delegate which is passed to this method will be called when the WaitHandle is released after being passed to the method. ``` ThreadPool.RegisterWaitForSingleObject(...) ``` There is a thread timer in .NET, and it differs from the WinForms/WPF timers in that its handler is called in the thread taken from the pool. ``` System.Threading.Timer ``` There is also a rather unusual way of sending the delegate to a thread from the pool – the BeginInvoke method. ``` DelegateInstance.BeginInvoke ``` I would also like to take a look at the function which many of the methods I mentioned earlier come down to – CreateThread from the Kernel32.dll Win32 API. There is a way to call this function with the help of the methods’ extern mechanism. I have only seen this being used once in a particularly bad case of legacy code – and I still don’t understand what its author’s reasons were. ``` Kernel32.dll CreateThread ``` #### Viewing and Debugging Threads All threads – whether created by you, third-party components or the .NET pool – can be viewed in the Visual Studio’s **Threads** window. This window will only display the information about threads when the application is being debugged in the Break mode. Here, you can view the names and priorities of each thread and focus the debug mode on specific threads. The Priority property of the Thread class allows you to set the thread’s priority. This priority will be then taken into consideration when the OS and CLR are dividing processor time between threads. ![](https://habrastorage.org/r/w1560/webt/ow/kq/i5/owkqi5zdx2m8oe7iava3q1mikri.png) #### Task Parallel Library Task Parallel Library (TPL) has first appeared in .NET 4.0. Currently, it’s the main tool for working with asynchrony. Any code utilizing older approaches will be considered legacy code. TPL’s main unit is the **Task** class from the System.Threading.Tasks namespace. Tasks represent thread abstraction. With the latest version of C#, we acquired a new elegant way of working with Tasks – the async/await operators. These allow for asynchronous code to be written as if it were simple and synchronous, so those who are not well-versed in the theory of threads can now write apps that won’t struggle with long operations. Using async/await is really a topic for a separate article (or even a few articles), but I’ll try to outline the basics in a few sentences: * async is a modificator of a method which returns a Task or void * await is an operator of a non-blocking wait Task. Once again: the await operator will usually (there are exceptions) let the current thread go and, when the task will be executed and the thread (actually, the context, but we’ll get back to it later) will be free as a result, it will continue executing the method. In .NET, this mechanism is implemented in the same way as yield return – a method is turned into a finite state machine class that can be executed in separate pieces based on its state. If this sound interesting, I would recommend writing any simple piece of code based on async/await, compiling it and looking at its compilation with the help of JetBrains dotPeek with Compiler Generated Code enabled. Let’s look at the options we have when it comes to starting and using a task. In the example below, we create a new task which doesn’t actually do anything productive(Thread.Sleep(10000)). However, in real cases we should substitute it with some complex work that utilizes CPU resources. ``` using TCO = System.Threading.Tasks.TaskCreationOptions; public static async void VoidAsyncMethod() { var cancellationSource = new CancellationTokenSource(); await Task.Factory.StartNew( // Code of action will be executed on other context () => Thread.Sleep(10000), cancellationSource.Token, TCO.LongRunning | TCO.AttachedToParent | TCO.PreferFairness, scheduler ); // Code after await will be executed on captured context } ``` A task is created with the following options: * LongRunning – this option hints at the fact that the task can not be performed quickly. Therefore, it is possibly better to create a separate thread for this task rather than taking an existing one from the pool to minimize harm to other tasks. * AttachedToParent – Tasks can be arranged hierarchically. If this option is used, the task will be waiting for its children tasks to be executed after being executed itself. * PreferFairness – this option specifies that the task should better be executed before the tasks that were created later. However, it’s more of a suggestion, so the result is not always guaranteed. The second parameter that was passed to the method is CancellationToken. For the operation to be properly cancelled after it was already started, the executable code should contain CancellationToken state checks. If there are no such checks, then the Cancel method called on the CancellationTokenSource object would only be able to stop the task execution before the task is actually started. For the last parameter, we sent a TaskScheduler-type object called scheduler. This class, along with its children classes, is used to control how tasks are distributed between threads. By default, a task will be executed on a randomly-selected thread from the pool The await operator is applied to the created task. This means that the code written after it (if there is such code) will be executed in the same context (often, this means ‘on the same thread’) as the code written before await. This method is labelled as async void, which means that the await operator can be used in it, but the calling code would no be able to wait for execution. If such possibility is needed, the method should return a Task. Methods labelled as async void can be seen quite often: they are usually event handlers or other methods operating under the fire and forget principle. If it’s necessary to wait for the execution to be finished and return the result, then you should use Task. For tasks that return the StartNew method, we can call ConfigureAwait with the false parameter – then, the execution after await will be continued on a random context instead of a captured one. This should always be done if the code written after await does not require a specific execution context. This is also a recommendation from MS when it comes to writing code provided as a library. Let’s look at how we can wait for a Task to be finished. Below, you can see an example piece of code with comments denoting when the waiting is implemented in a relatively good or bad manner. ``` public static async void AnotherMethod() { int result = await AsyncMethod(); // good result = AsyncMethod().Result; // bad AsyncMethod().Wait(); // bad IEnumerable tasks = new Task[] { AsyncMethod(), OtherAsyncMethod() }; await Task.WhenAll(tasks); // good await Task.WhenAny(tasks); // good Task.WaitAll(tasks.ToArray()); // bad } ``` In the first example, we are waiting for the Task to be executed without blocking the calling thread, so we’ll come back to processing the result when it’s ready. Before that happens, the calling thread is left on its own. In the second attempt, we are blocking the calling thread until the method’s result is calculated. This is a bad approach for two reasons. First of all, we are wasting a thread – a very valuable resource – on simple waiting. Additionally, if the method we’re calling contains an await while a return to the calling thread after await is intended by the synchronization context, we’ll get a deadlock. This happens because the calling thread will be waiting for the result of an asynchronous method, and the asynchronous method itself will be fruitlessly trying to continue its execution in the calling thread. Another disadvantage of this approach is the increased complexity of error handling. The errors can actually be handled rather easily in asynchronous code if async/await is used – the process in this case is identical to that in synchronous code. However, when a synchronous wait is applied to a Task, the initial exception is wrapped in AggregateException. In other words, to handle the exception, we would need to explore the InnerException type and manually write an if chain in a catch block or, alternatively, use the catch when structure instead of the more usual chain of catch blocks. The two last examples are also labelled as relatively bad for the same reasons and both contain the same issues. The WhenAny and WhenAll methods are very useful when it comes to waiting for a group of Tasks – they wrap these tasks into one, and it will be executed either when one Task from the group is started or when all of these tasks are successfully executed. #### Stopping Threads For various reasons, there may be a need to stop a thread after it has been started. There are a few ways to do this. The Thread class has two methods with appropriate names — **Abort** and **Interrupt**. I would strongly discourage using the first one as, after it’s called, there would be a **ThreadAbortedException** thrown at any random moment while processing any arbitrarily chosen instruction. You’re not expecting such an exception to be encountered when an integer variable is incremented, right? Well, when using the Abort method, this becomes a real possibility. In case you need to deny the CLR’s ability of creating such exceptions in a specific part of the code, you can wrap it in the **Thread.BeginCriticalRegion** and **Thread.EndCriticalRegion** calls. Any code written in the finally block is wrapped in these calls. This is why you can find blocks with an empty try and a non-empty finally in the depths of the framework code. Microsoft dislike this method to the extent of not including it in the .NET core. The **Interrrupt** method works in a much more predictable way. It can interrupt a thread with a **ThreadInterruptedException** only when the thread is in the waiting mode. It moves to this state when suspended while waiting for WaitHandle, a lock or after Thread.Sleep is called. Both of these ways have a disadvantage of unpredictability. To escape this issue, we should use the **CancellationToken** structure and the **CancellationTokenSource** class. The general idea is this: an instance of the CancellationTokenSource class is created, and only those who own it can stop the operation by calling the **Cancel** method. Only CancellationToken is passed to the operation. CancellationToken’s owners cannot cancel the operation themselves – they can only check whether the operation has been cancelled. This can be achieved by using a Boolean property **IsCancellationRequested** and the **ThrowIfCancelRequested** method. The last one will generate a **TaskCancelledException** if the Cancel method has been called on the CancellationTokenSource instance which created the CancellationToken. This is the method I recommend using. It’s advantage over the previously-described methods lies in the fact that it provides full control over the exact exception cases in which an operation can be cancelled. The most brutal way to stop a thread would be to call a Win32 API function called TerminateThread. After this function is called, the CLR’s behavior can be quite unpredictable. In [MSDN](https://docs.microsoft.com/en-us/windows/desktop/api/processthreadsapi/nf-processthreadsapi-terminatethread), the following is written about this function: *“TerminateThread is a dangerous function that should only be used in the most extreme cases. “* #### Turning a Legacy API Into a Task-Based One by Using FromAsync If you were fortunate enough to work on a project which was started after the Tasks have been introduced (and when they are no longer inciting existential horror in most of developers), you will not have to deal with old APIs – both the third-party ones and those your team toiled on in the past. Fortunately, the .NET Framework development team made it easier for us – but this could have been self-care, for all we know. In any case, .NET has a few tools which help with seamlessly bringing the code written with old aprroaches to asynchrony in mind to an up-to-date form. One of these is the TaskFactory method called FromAsync. In the example below, I’m wrapping the old asynchronous methods of the WebRequest class into a Task by using FromAsync. ``` object state = null; WebRequest wr = WebRequest.CreateHttp("http://github.com"); await Task.Factory.FromAsync( wr.BeginGetResponse, we.EndGetResponse ); ``` *It’s only an example, and you probably won’t be doing something of this sort with built-in types. However, old projects teem with BeginDoSomething methods that return IAsyncResult and EndDoSomething methods that receive them.* #### Turning a Legacy API Into a Task-Based One by Using TaskCompletionSource Another tool worth exploring is the **TaskCompletionSource** class. In its functionality, purpose and operation principle, it resembles the RegisterWaitForSingleObject method from the ThreadPool class I mentioned earlier. This class allows us to easily wrap old asynchronous APIs into Tasks. *You may want to say that I already told about the FromAsync method from the TaskFactory class which served these purposes. Here, we would need to remember the full history of asynchronous models Microsoft provided in the last 15 years: before Task-Based Asynchronous Patterns (TAP), there were Asynchronous Programming Patterns (APP). APPs were all about **Begin**DoSomething returning IAsyncResult and the **End**DoSomething method which accepts it – and the FromAsync method is perfect for these years’ legacy. However, as time passed, this was replaced with Event Based Asynchronous Patterns(EAP) which specified that an event is called when an asynchronous operation is successfully executed.* TaskCompletionSource are perfect for wrapping legacy APIs built around the event model into Tasks. This is how it works: objects of this class have a public property called Task, the state of which can be controlled by various methods of the TaskCompletionSource class (SetResult, SetException etc.). In places where the await operator was applied to this Task, it will be executed or crashed with an exception depending on the method applied to TaskCompletionSource. To understand it better, let’s look at this example piece of code. Here, some old API from the EAP era is wrapped in a Task with the help of TaskCompletionSource: when an event is triggered, the Task will be switched to the Completed state while the method that applied the await operator to this Task will continue its execution after receiving a **result** object. ``` public static Task DoAsync(this SomeApiInstance someApiObj) { var completionSource = new TaskCompletionSource(); someApiObj.Done += result => completionSource.SetResult(result); someApiObj.Do(); result completionSource.Task; } ``` #### TaskCompletionSource Tips & Tricks TaskCompletionSource can do more than just wrapping obsolete APIs. This class opens an interesting possibility of designing various APIs based on Tasks that don’t occupy threads. A thread, as we remember, is a expensive resource limited mostly by RAM. We can easily reach this limit when developing a robust web application with complex business logic. Let’s look at the capabilities I mentioned in action by implementing a neat trick known as Long Polling. **In short, this is how Long Polling works:** *You need to get some information from an API about events occurring on its side, but the API, for some reason, can only return a state rather than telling you about the event. An example of such would be any API built over HTTP before WebSocket appeared or in circumstances under which this technology can’t be used. The client can ask the HTTP server. The HTTP server, on the other hand, cannot initiate contact with the client by itself. The simplest solution would be to ask the server periodically using a timer, but this would create additional load for the server and a general delay which approximately equals to TimerInterval / 2. To bypass this, Long Polling was invented. It entails delaying the server response until the Timeout expires or an event happens. If an event occurs, it will be handled; if not – the request will be sent again.* ``` while(!eventOccures && !timeoutExceeded) { CheckTimout(); CheckEvent(); Thread.Sleep(1); } ``` However, this solution’s effectiveness will radically drop should the number of clients waiting for the event grow – each waiting client occupies a full thread. Also, we get an additional delay of 1ms for event triggering. Often, it’s not really that crucial, but why would we make our software worse than it could be? On the other hand, if we remove Thread.Sleep(1), one of the CPU cores will be loaded for the full 100% while doing nothing in a useless cycle. With the help of TaskCompletionSource, we can easily transform our code to resolve all of the issues we mentioned: ``` class LongPollingApi { private Dictionary> tasks; public async Task AcceptMessageAsync(int userId, int duration) { var cs = new TaskCompletionSource(); tasks[userId] = cs; await Task.WhenAny(Task.Delay(duration), cs.Task); return cs.Task.IsCompleted ? cs.Task.Result : null; } public void SendMessage(int userId, Msg m) { if (tasks.TryGetValue(userId, out var completionSource)) completionSource.SetResult(m); } } ``` *Please keep in mind that this piece of code is only an example, and in no way production-ready. To use it in real cases, we would at least need to add a way to handle situations in which a message is received when nothing was waiting for it: in this case, the AcceptMessageAsync method should return an already finished Task. If this case is the most common one, we can consider using ValueTask.* When receiving a message request, we create a TaskCompletionSource, place it in a dictionary, and then wait for one of the following events: either the specified time interval is spent or a message is received. #### ValueTask: Why and How async/await operators, just like the yield return operator, generate a finite state machine from a method, which means creating a new object – this doesn’t really matter most of the time, but can still create issues in some rare cases. One of these cases can occur with frequently-called methods – we’re talking tens and hundreds of thousands calls per second. If such a method is written in a way which makes it return the result while bypassing all await methods in most of the cases, .NET provides an optimization tool for this – the ValueTask structure. To understand how it works, let’s look at an example. Suppose there is a cache we access on a regular basis. If there are any values in it, we just return them; if there are no values – we try to get them from some slow IO. The latter should ideally be done asynchronously, so the whole method will be asynchronous. So, the most obvious way to implement this method will be as follows: ``` public async Task GetById(int id) { if (cache.TryGetValue(id, out string val)) return val; return await RequestById(id); } ``` With a desire to optimize it a little bit and a concern for what Roslyn will generate when compiling this code, we could re-write the method like this: ``` public Task GetById(int id) { if (cache.TryGetValue(id, out string val)) return Task.FromResult(val); return RequestById(id); } ``` However, the best solution in this case would be to optimize hot-path – specifically, getting dictionary values with no unnecessary allocations and no load on GC. Meanwhile, in those infrequent cases when we need to get data from IO, things will remain almost the same: ``` public ValueTask GetById(int id) { if (cache.TryGetValue(id, out string val)) return new ValueTask(val); return new ValueTask(RequestById(id)); } ``` Let’s look at this code fragment more closely: if a value is present in the cache, we’ll create a structure; otherwise, the real task will be wrapped in a ValueTask. The path by which this code is executed is not important for the calling code: from the perspective of C# syntax, a ValueTask will behave just like a usual Task. #### TaskScheduler: Controlling Task Execution Strategies The next API I’d like to talk about is the **TaskScheduler** class and those derived from it. I already mentioned that TPL provides an ability to control how exactly Tasks are being distributed between threads. These strategies are defined in classes inheriting from TaskScheduler. Almost any strategy we may need can be found in the **ParallelExtensionsExtras** library. This library is developed by Microsoft, but is not a part of .NET – rather, it’s distributed as a Nuget package. Let’s have a look at some of the strategies: * CurrentThreadTaskScheduler – executes Tasks on the current thread * LimitedConcurrencyLevelTaskScheduler – limits the number of concurrently executed Tasks by using the N parameter which it accepts in the constructor * OrderedTaskScheduler – is defined as LimitedConcurrencyLevelTaskScheduler(1), so Tasks will be executed sequentially. * WorkStealingTaskScheduler – implements the [work-stealing](https://en.wikipedia.org/wiki/Work_stealing) approach to task execution. Essentially, it can be viewed as a separate ThreadPool. This helps with the issue of ThreadPool being a static class in .NET — if it’s overloaded or used improperly in one part of the application, unpleasant side effects may occur in a different place. Real causes of such defects can be difficult to locate, so you may need to use separate WorkStealingTaskSchedulers in those parts of the application where ThreadPool usage can be aggressive and unpredictable. * QueuedTaskScheduler – allows to execute tasks on a basis of a prioritized queue * ThreadPerTaskScheduler – creates a separate thread for each Task that’s executed on it. This can be helpful for tasks the execution time of which cannot be estimated. There is a very good [article](https://devblogs.microsoft.com/pfxteam/parallelextensionsextras-tour-7-additional-taskschedulers/) about TaskSchedulers on Microsoft’s blog, so feel free to check it out. In Visual Studio, there is a Tasks window which can help with debugging everything related to Tasks. In this window, you can see the task’s state and jump to the currently executed line of code. ![](https://habrastorage.org/r/w1560/webt/tb/fv/3l/tbfv3l-sdz-jw0mpcakbt_-lve8.png) #### PLinq and the Parallel Class Aside from Tasks and all things related to them, there are two additional tools in .NET we can find interesting – **PLinq**(Linq2Parallel) and the **Parallel** class. The first one promises parallel execution of all Linq operations on all threads. The number of threads can be configured by an extension method WithDegreeOfParallelism. Unfortunately, in most cases, PLinq in the default mode will not have enough information about the data source to provide a significant increase in speed. On the other hand, the cost of trying is very low: you only need to call **AsParallel** before the chain of Linq methods and carry out performance tests. Moreover, you can pass additional information about the nature of your data source to PLinq by using the Partitions mechanism. You can find more information [here](https://devblogs.microsoft.com/pfxteam/partitioning-in-plinq/) and [here](https://docs.microsoft.com/en-us/dotnet/standard/parallel-programming/custom-partitioners-for-plinq-and-tpl). The Parallel static class provides methods for enumerating collections in parallel via Foreach, running the For cycle and executing several delegates in parallel to Invoke. Execution of the current thread will be stopped until the results are calculated. You can configure the number of threads by passing ParallelOptions as the last argument. TaskScheduler and CancellationToken can also be set with the help of options. ### Summary When I started writing this article based on my thesis and on the knowledge I gained while working after it, I didn’t think there would be this much information. Now, with the text editor reproachfully telling me that I’ve written almost 15 pages, I’d like to draw an intermediary conclusion. We will look at other techniques, APIs, visual tools and hidden hazards in the next article. **Conclusions:** * To effectively use the resources of modern PCs, you would need to know tools for working with threads, asynchrony and parallelism. * There are many tools like this in .NET * Not all of them were created at the same time, so you may often encounter some legacy code – but there are ways of transforming old APIs with little effort. * In .NET, the Thread and ThreadPool classes are used for working with threads * The Thread.Abort and Thread.Interrupt method, along with the Win32 API function TerminateThread, are dangerous and not recommended for use. Instead, it’s better to use CancellationTokens * Threads are a valuable resource and their number is limited. You should avoid cases in which threads are occupied by waiting for events. The TaskCompletionSource class can help achieve this. * Tasks are the most powerful and robust tool .NET has for working with parallelism and asynchrony. * The async/await C# operators implement the concept of a non-blocking wait * You can control how Tasks are distributed between threads with the help of classes derived from TaskScheduler * The ValueTask structure can be used to optimize hot-paths and memory-traffic * The Tasks and Threads windows in Visual Studio provide a lot of helpful information for debugging multi-threaded or asynchronous code * PLinq is an awesome tool, but it may not have all required information about your data source – which can still be fixed with the partitioning mechanism *To be [continued](https://habr.com/post/461471/)…*
https://habr.com/ru/post/455252/
null
null
5,393
52.29
# A Simple Way to Talk To Your Website ![image](https://habrastorage.org/r/w1560/getpro/habr/post_images/0a9/349/283/0a93492833d662755a1274829549872b.png) Technology and markets are going hand in hand today. It's going so close that any whiff of a tech headway and social media is going up in a frenzy about it. Writers are filling pages after pages as if it's already here. Shares ride bull or bear, and newspapers print a string of capital letters. The pitfall of such journalistic overreaction is that we miss out on many simple tools, many small but innovative ideas that surround our networking space. An eye on the future makes us blind to the opportunity in the present moment. Web developing companies are urging digital marketing leads to writing more about the possibility of [blockchains transforming the world](https://habr.com/en/post/441420/) or how Artificial Intelligence is the next biggest thing. They are missing something very innovative and prospective. It is the ability to make your website interactive. Imagine talking to your website to make your favourite pick the background. Your site answering you could be Artificial Intelligence, but you don’t need to go that far to speak to your website. The tool is there sleeping in your browser, and you are not even aware. We are talking about Google's Web Speech API. Let us first look at some essential elements of speech before we delve deeper into Google Web Speech APIs Some Fundamentals of Speech --------------------------- Now, to speak is easy, even a child can talk, but speech recognition is not a child’s play. Our mind and its relation to the brain is much more complicated than was assumed. Hence, computers though exceptional in some aspects is nowhere near human brain in perception. Computers need much help to listen to words as speech is not a walk in the park. Speech is a complex phenomenon to study. It gets stranger as we go deeper into it. Speech hence is not merely an assortment of words stringed together. Every time we speak our utterance contains packets of sound which is called a phone. For example: when we say the word “MAT” we utter phones ‘m’, ‘a’, ‘t’. But the actual way we speak a sound and how our mind conceives it is entirely different. Do you remember those instances, when you react even before the completion of a sentence? You did it because there are some fundamental blocks of sound that your mind perceives unconsciously, these elements are called phonemes. In addition to it, there are diverse elements of linguistics that one has to consider. For example, the syntax which elaborates the grammatical structure of a language and the semantics — the meaning of words — and how they churn out their holistic meaning of a sentence. How Computers Listen To You? ---------------------------- The speech recognition is an interdisciplinary science and combines the subtle concepts from linguistics, signal processing, natural language processing and much more. For simplicity’s sake we need to consider the following approaches to understanding the way computers interpret speech: ### 1. Pattern Matching You might remember the computerised voice of your gas booking station asking you to choose by pressing 1 or 2 in your mobile keypad to book a new gas cylinder. It is done using this technique were the computer trained to differentiate ten sound patterns. The “one”, “zero”, “ten” etc. are the sounds that are detected in this pattern matching exercise. A computer matches the blocks of sound already stored in memory to further actions. That’s why you hear “Sorry, We Didn’t Get You” when you speak zero a little casually. ### 2. Analysis of Feature and Patterns A typical speech recognition tool can conceive a large vocabulary of sounds. You may wonder how it does it? The moment you speak into your mic an A/D converter (Analogue/Digital), converts the vibrations into digital texts. The spectrogram then plots the digital data into a graph, using a signal processing technique called FTT( Fast Fourier Transform). Then the waveform is broken into overlapping blocks called acoustic frames — the separation created by using a time gap of 1/50th of a second or 1/25th of a second. Here the speech is broken into possible words and is then compared with a phonetic dictionary and thus pinpoint the word spoken. ### 3. Statistical Method The way each person utters a word is uniquely different. Even the same person may pronounce the same word differently another time. Hence, a system that has to decipher essential elements out of a large pool has to deal with the problem of variability. The modern speech recognition tools utilise language models to deal with the issue of variability. Models like the Hidden Markov Model(HMV), uses probabilistic guessing using grammatical laws to arrive at the most likely word. It refines its accuracy by expanding on even the smallest sound that gets captured. The word example is preceded in English by a very selective number of words like, ‘for’, ‘bad’ ,’good’, etc. If the recognition process hangs at say “ It is a \_\_\_ example.” And a slight sound like ‘g’ was identified then the system rounds up the blank word to mean ‘good.’ ### 4. Artificial Neural Networks They are simplified human brains that are capable of learning through examples. Hence, if the ANNs are trained with enough samples, then it can correlate it with previously seen patterns to arrive at the right word. So a fully trained Neural Network can take speech recognition to a different level. Here’s How You Can Modify Your Site ----------------------------------- We will use the Web Speech API that was developed by the W3C community in 2012. Many browsers do not utilise it for one or the other reason. But Chrome and Firefox have integrated this into their browsers, and that’s why you can voice search on Google. The Web Speech API will be our interface that already has other closely linked aspects of speech like the grammar, vocabulary etc. Your tool will look like the one above. All you need to do execute this code. The CSS code below gives the design to your recognition feature the colour and display features. Here only a simple model is presented. You can give expression to your creativity by altering the CSS codes. ``` html, body { display: flex; align-items: center; justify-content: center; background-color: lightblue; } .record { position: relative; width: 246px; display: inline-block; } .record input { text-align:center; border: 0; width: 240px; display: inline-block; height: 30px; } .record img { float: right; width: 25px; height: 25px; border: none; position: absolute; right: 7px; top: 3px; } .container { display: inline-block; text-align: center; } h1 { font-family: constantia; } ``` The next set of codes will call the API to do the actual speech recognition for you. The necessary HTML and Java scripts are included in the set. ``` Voice Recognition: Habr Voice Recognition in HTML ========================= ![](http://icons.iconarchive.com/icons/designbolts/free-multimedia/1024/Studio-Mic-icon.png) function startRecording() { if (window.hasOwnProperty('webkitSpeechRecognition')) { var recognition = new webkitSpeechRecognition(); recognition.continuous = false; recognition.interimResults = false; recognition.lang = "en-US"; recognition.start(); recognition.onresult = function(e) { document.getElementById('transcript').value = e.results[0][0].transcript; recognition.stop(); document.getElementById('speak-form').submit(); }; recognition.onerror = function(e) { recognition.stop(); } } } ``` The simple tool described above can open up a new window of opportunity to many sites that are struggling to be interactive and unique. Web development should implement such simple and scalable techniques first. Intelligent web development should find the right balance between [crucial web design secrets](https://mindster.com/9-crucial-web-design-secrets-develop-professional-website) and such simple integrative tools. The Web API can further be used in mobile app development to enhance smartphones and make them smart. So check out this feature now and have a good time chatting with your website.
https://habr.com/ru/post/446056/
null
null
1,312
56.96
US CompSci Enrollment Up For 4th Year Running timothy posted more than 2 years ago | from the so-hone-that-application-essay dept. ." frosty piss up for the 4th year (-1) Anonymous Coward | more than 2 years ago | (#39630445) for loops galore (3, Insightful) Anonymous Coward | more than 2 years ago | (#39630473) Get back to us after the fourth semester and let us know what % of the enrolled did not switch majors or drop out. Re:for loops galore (0) Anonymous Coward | more than 2 years ago | (#39634589) If they drop out they can still get a lucrative career in IT where computer science doesn't matter. Probably the whole reason for the increase in enrollment is that they're thinking this is the way to get a high tech 9-5 job. Lesson 1: learn to say "we need more RAM and disk space" Lesson 2: learn to say "we should migrate to the cloud" Lesson 3: Head to Microsoft certification classes to learn the minimal amount of technician skills to get a generic job. Actually it's better this way. If you actually know your stuff you're not likely to be well respected at a large IT grunt shop. This, kind of. (0) Anonymous Coward | more than 2 years ago | (#39635523) Went CS; dropped out after not getting along with ridiculously advanced calculus; ended up with an AS in 'Computer Information Systems', whatever the hell that is, solely for the purpose of having some sort of college degree. My thoughts are fought over by many; my words turn the course of businesses; my legend glows like the heat of ten thousand stars. And never once have I had cause to use that class on binary math I encountered during my CS days. CS is completely useless to the average IT person. We're not talking loltechsupport, either. Systems architecture, administration, developers, designers, management - none of these people need a CS degree. What a pity our education system hasn't clued clueless high school students in on that. Re:This, kind of. (1) lorenlal (164133) | more than 2 years ago | (#39636145) of that is particularly advanced, so... No, you can probably get by just fine without a CS degree in IT... But it doesn't hurt. For some of us, it opened our eyes to how much we didn't know. I grew up loving to take apart my computer and put it back together... But I didn't exactly have much exposure to anything to help me pick up programming on my own. My CS degree ended up being a lot of fun, pretty educational, and pretty useful to me. I'd even say that I did indeed need the degree, or at least the experience I gained while earning it. I went, I learned, I conquered those stinking 4 semesters of Calc (barely), and I wouldn't have had access to computing resources like that outside of my university setting. Oh, and it did help me impress a Math PhD who is now my wife. I occasionally help her code up some of her research. Works just fine for me. You need a degree (1) Dainsanefh (2009638) | more than 2 years ago | (#39636159) But you need some sort of Bachelor's degree to get MBA, which allows you to do all the above with job security and 6-figure pay. 10/360 enrolled made it (CSC degree track) (0) Anonymous Coward | more than 2 years ago | (#39654835) That sounds pretty much like the CSC trackrecord I saw during my schooling for CSC degree (2nd one, I have B.S. MIS earlier on): At the start, there were something like 360 CSC majors declared... @ the end? * Only 10 of us made it... from my class. My best pal @ the time, A Russian-Jewish immigrant whom my family "took a shine to" because they too were immigrants (1st generation U.S. Citizen here), & I, were the ONLY ones recommended for jobs by the CSC dept. head & with a then "Fortune 500" company too (Goulds Pumps) Man - but, we did NOTHING but "live the job" is why... & it showed in grades, and work efforts... However - I look back NOW though, & think to myself @ times: "College is illogical - you work hard AND PAY FOR IT, rather than working hard & GETTING PAID" Lol... but, that's the "price of the caste system" (in today's world!) APK P.S.=> However, if you "live the job" (I mean put in TONS more time than just what school demands, & to get "A's" for every 1 hour of class time, you had better put in 3 more on your own)? You'll excel... guaranteed. By "live the job" as far as being a student (and in "the real working world" later)? It means really putting your heart, soul, & TIME (the most important commodity we have as "mortals") into it... apk I'm sorry guys! (-1) Anonymous Coward | more than 2 years ago | (#39630487) I'm sorry, but I have to get this off my chest after all these years. I was...the one you gave Steve Jobs AIDS. I have been HIV positive for nearly a decade and I knew I shouldn't have had sex with him in the bathhouse that night, but when we started stroking my shaft and fingering my prostate I lost all sense of reason. I told him we should use a condom 'just in case' but he demanded that I plow him bareback and I couldn't help but to orgasm in his asshole. A few months later was when he first started having health issues and I've felt bad ever since. Re:I'm sorry guys! (2) tom17 (659054) | more than 2 years ago | (#39630541) I know I'm not meant to reply to this, but please, if you are going to do this, *please* fix the grammar. Sentence two you no sense. Re:I'm sorry guys! (1) ciderbrew (1860166) | more than 2 years ago | (#39630875) Re:I'm sorry guys! (2) tom17 (659054) | more than 2 years ago | (#39631533) (2, Interesting) Joe_Dragon (2206452) | more than 2 years ago | (#39630503) and how meany people are better off voc / tech school type training then 4 years + of CS? To many people are going to CS and not learning the skills needed to do real IT work. Re:and how meany people are better off voc / tech (5, Insightful) Xphile101361 (1017774) | more than 2 years ago | (#39630537) Re:and how meany people are better off voc / tech (3, Insightful) danbuter (2019760) | more than 2 years ago | (#39630563) Re:and how meany people are better off voc / tech (1) Darinbob (1142669) | more than 2 years ago | (#39634631) (4, Informative) mx+b (2078162) | more than 2 years ago | (#39630633):Students Don't Always Know The Difference (1) Vahokif (1292866) | more than 2 years ago | (#39631067) Re:Students Don't Always Know The Difference (1) I Read Good (2348294) | more than 2 years ago | (#39632683) Re:Students Don't Always Know The Difference (0) Anonymous Coward | more than 2 years ago | (#39640593) That's distinguishing between CS and more CS, not between CS and IT. also CS can be very different from school to schoo (0) Anonymous Coward | more than 2 years ago | (#39631317) also CS can be very different from school to school. some are very theoretical based with little hands on. other are more focused on the programming. But even then there are many areas in the programming area. Also how does a very focused on the programming 4 year plan help VS a tech school / Votech at maybe 2 years. Help you on Cisco? helpdesk / desktop? system admin work? web? networking? There is a lot in IT that you can pick up better doing it on the job VS 4 years in a class room. Now with CS you may be a jack of all trades on a theoretical level. VS say a tech school where you may be focused on say 2-3 on the listed befor areas with some hands on idea of the other skills needed. But going to a school with a big focused on the programming does not really help you be better at IT admin work. Re:Students Don't Always Know The Difference (1) chuckinator (2409512) | more than 2 years ago | (#39631479) Re:Students Don't Always Know The Difference (3, Interesting) Shimdaddy (898354) | more than 2 years ago | (#39634141). IT jobs == CS degree. (-1) Anonymous Coward | more than 2 years ago | (#39631781) When you go for any IT job, the number one requirement these days is a degree in Computer Science or engineering (which I find idiotic. Engineers are shitty programmers.). If you want an IT job you need a CS degree. You can post until he cows turn blue in the face and your face comes home about how Computer Science is a science and it's about algorithms and yadda yadda yadda. Whatever. A BSCS means that you're just qualified to do grunt IT work. You are NOT a Computer Scientist until you get a Ph.D. God! Get over yourselves. Re:IT jobs == CS degree. (1) GonzoPhysicist (1231558) | more than 2 years ago | (#39631913) Re:IT jobs == CS degree. (0) Anonymous Coward | more than 2 years ago | (#39633789) You are NOT a Computer Scientist until you get a Ph.D. You do know that school isn't the only place to learn, right? You do know that you can, for instance, learn about something outside of school, or purely through experience, right? If it can be learned in school, it can be learned outside of it. Most likely. Re:IT jobs == CS degree. (3, Informative) NotSanguine (1917456) | more than 2 years ago | (#39634001) When you go for any IT job, the number one requirement these days is a degree in Computer Science or equivalent experience. There. FTFY. Re:Students Don't Always Know The Difference (2) negativeduck (2510256) | more than 2 years ago | (#39632037) Re:Students Don't Always Know The Difference (5, Interesting) tomhath (637240) | more than 2 years ago | (#39633715) Re:Students Don't Always Know The Difference (1) Darinbob (1142669) | more than 2 years ago | (#39634955) the only entry level jobs are to do are QA or help desk support, at a company where the only upward mobility is into IT jobs rather than development. And that's not even counting the mediocre students who spent the whole time thinking "no one ever needs to know this rubbish." This isn't new, just look at the movie The Graduate with "plastics" advice being offered. When I started university in early 80s there was a very similar feeling and I met a lot of fellow students who I think were told "I have just one word for you son, Computers!" And the department was overfilled and students were being turned away from required classes. Just all this mania about getting into computers. Re:Students Don't Always Know The Difference (1) Ihmhi (1206036) | more than 2 years ago | (#39634863):and how meany people are better off voc / tech (0) Anonymous Coward | more than 2 years ago | (#39631273) Lets be realistic, CS majors have two paths to go once they get their diploma: They can be a developer and try to fight for every dollar earned against Indians/Chinese who are ready/willing/able to work for pennies on the dollar. For them, a $30,000 annual salary for a CCIE certification is more than enough for a H-1B, because an efficiency apartment isn't glamorous, but it beats the slums or rice paddys any day of the week. They can go the IT route. Yes, one has to fight against the H-1Bs who will work for any price, but there are jobs available -- someone has to be local and watch the routers, even if it is working for Geek Squad. Want to know how to make money with a CS degree? Use it to fulfill the law school prerequesite and get your J. D. There are plenty of jobs available for people who both know Sarbanes-Oxley and other regulations without having to tack on "IANAL" behind every statement. Then, there is IP law. There is no such thing as an unemployed lawyer. Trust me, law is the only money maker in the US (if you want a career, not just a job), and people who don't get this are just plain deluded. Lawyers made the Constitution while doctors were still believing in the four humors and using leeches. Re:and how meany people are better off voc / tech (2) hackula (2596247) | more than 2 years ago | (#39631907) Re:and how meany people are better off voc / tech (1) Trepidity (597) | more than 2 years ago | (#39632099) In general lawyers are currently over-supplied, but lawyers who have a STEM degree in addition to their JD aren't. Still a pretty significant demand for patent law and that kind of thing. Re:and how meany people are better off voc / tech (1) NJRoadfan (1254248) | more than 2 years ago | (#39632135) Re:and how meany people are better off voc / tech (2) azadrozny (576352) | more than 2 years ago | (#39632681) Re:and how meany people are better off voc / tech (0) Anonymous Coward | more than 2 years ago | (#39633525) See you are asking a very primitive cognitive ability actually the lowest one, whether someone can remember something. That is fucking great you know what inheritance and all the OO concepts but you don't have a fucking clue how to apply them hence the reason why you have copy and pasted the same fucking class 10 times. Oh and you created race condition because you heard about multi threaded programming and wanted to try it out sof you can fill in that buzzword on you resume. And along with that you create memory leak. Oh I see knowing a bunch of facts is more important that actually being able to solve problems. Crappy programmers that rattle off buzzwords but don't really have an idea how to program or design a system well eventually they stay somewhere so long eventually the manager has them do interviews even though they still are a crappy programmer that is going to rattle off buzzwords to make their penis look bigger. Re:and how meany people are better off voc / tech (1) azadrozny (576352) | more than 2 years ago | (#39635359) how your experience applies. Or if the job description mentions a specific commercial software package, I expect that you have read up on in it and know generally what the product does. In that same vein, if I ask if you have ever done multi-threaded programming, or how would you troubleshoot a race condition, you are going to need to know the definition to answer the question. In short, good programmers do know the definition of basic concepts, and can relate it to their past experience, and good candidates do research before they walk in the door. Re:and how meany people are better off voc / tech (1) gstoddart (321705) | more than 2 years ago | (#39633751) make sure he was up to the task. He was an atrocious programmer -- the first task I gave him took him several days to code, and it was badly implemented and incredibly slow. After he argued with me that his was just as good as mine (which I knocked up in 30 minutes). Sadly, the few Admin tasks we let him do he didn't really shine at either. He didn't last long after that because he refused to understand that his half-assed attempt wasn't as good as we needed. I also once worked with an electrical engineer who had been hired as a coder. He didn't actually *know* anything about writing code, and eventually became a placeholder position. We had assumed that as an EE he knew these things, and he had assumed we'd teach him.. Re:and how meany people are better off voc / tech (1) NJRoadfan (1254248) | more than 2 years ago | (#39634929):and how meany people are better off voc / tech (1) gstoddart (321705) | more than 2 years ago | (#39635463) several years I was in school. So I did some specialized programming and the like (bare metal, OS kind of stuff) , had done code walkthroughs, and almost all of my courses had a really heavy coding quotient. So I crawled around in more code than some friends with Master's degrees since more of their stuff was theoretical, or only had to work well enough to cover their specific area of research -- you can still do cool research and write crap code if nobody else has to see it or maintain it. In all honesty, by the end of my degree, there were people in my department who I was convinced managed to do most of the course work and pass, but who nonetheless weren't very good programmers. Give them a well defined problem and some help, they can do it -- go much beyond that, and they didn't seem to know much. I also know several people who only formally have high-school, but are absolute rock stars when it comes to writing code. I am actually surprised at how many people out of school I've met who have never used anything like CVS, never built anything more complex than a little demo, and only really have a semester's worth of coding with everything else being theoretical. I've also seen people who had an OK high-level view of computers, but didn't really understand how an OS actually worked or anything like that. Often concepts like testing and documenting make them turn up their nose as if it's beneath them -- sorry, but we can't use you if you can't see why we do these things. I've also seen people who don't seem to have any measurable skill at debugging programs and trouble-shooting. Years after I graduated, the prof I did my research work with and I were having a chat -- he asked me if I ever actually used anything he'd taught me. I could tell him in all honesty that the stuff I'd learned from him about programming and building/designing stuff I used every single day of my life. So, I was fortunate in that I got to learn a lot of the intangible stuff we didn't cover in class. I got to learn by going through the process and being shown how these things are done. So, my best advise? Build something. Be ready to show it. Actual working code is probably better than your resume if you're just starting out. Perspective employers need to know that you have more than a passing/theoretical knowledge about how to program. And they also need to believe that you're capable of learning things you may not know very well. Re:and how meany people are better off voc / tech (1) Darinbob (1142669) | more than 2 years ago | (#39635247) this to say accounting. There are a lot of accountants who do not want to do people's taxes, and yet they know that during tax season that there will almost always be an open job doing that. But you don't advance your dream job of being a business accountant by taking a job at H&R Block. (And employers for the most part don't really want Java programmers, they want Java *framework* programmers. You won't get a job knowing only the language though you may get calls from recruiters.) Re:and how meany people are better off voc / tech (0) Anonymous Coward | more than 2 years ago | (#39630551) What are those skill needed to do real IT work? Re:and how meany people are better off voc / tech (0) Anonymous Coward | more than 2 years ago | (#39630609) Googling and being able to type fast. Re:and how meany people are better off voc / tech (1) vlm (69642) | more than 2 years ago | (#39630815):and how meany people are better off voc / tech (1) hackula (2596247) | more than 2 years ago | (#39631971) Re:and how meany people are better off voc / tech (2) vlm (69642) | more than 2 years ago | (#39630717) only needs pub speaking as an oral defense at the PHD and teaching classes. A foreign language (aka BA degree) seems highly wise for IT as your job will probably go to India or China very soon, so if you learn hindi or mandarin perhaps you can transfer into a project mismanagement or perhaps analyst position... IT needs to learn how to master a piece of software and/or a system. The software selected to master doesn't really matter, whats important is that some people, shockingly, don't know how to explore and fully learn a piece of software unless that skill is specifically taught to them. Like many, maybe most, computer people, I learned that around age 6, but there's some who need the formal class to learn it at age 20. IT needs database theory, a computer scientist only needs codd normal forms etc if s/he is going into the DB theory field (frankly, unlikely). Very little of a CS curriculum would be a total waste of time for a IT guy and vice versa, but a lot of mandatory and nice to have positions will swap. Re:and how meany people are better off voc / tech (1) Dainsanefh (2009638) | more than 2 years ago | (#39636215) A combined IT / MBA curriculum seems more make sense. Political Science is also a plus. But in the USA there are too many white IT racist that refuse to learn another language. Re:and how meany people are better off voc / tech (1) na1led (1030470) | more than 2 years ago | (#39630569) Re:and how meany people are better off voc / tech (1) Sir_Eptishous (873977) | more than 2 years ago | (#39630647) Re:and how meany people are better off voc / tech (1) MindStalker (22827) | more than 2 years ago | (#39630923) was single I'd freelance solely. Re:and how meany people are better off voc / tech (1) na1led (1030470) | more than 2 years ago | (#39631581) Re:and how meany people are better off voc / tech (0) Anonymous Coward | more than 2 years ago | (#39631451) I'd agree here. To a tech savvy manager, they are more interested in skill than certs. However, to the people that hire the purse strings, they don't see that. All they care about is that the person has the alphabet soup of characters after their name, be it a B. S., MCSE, CCIE, CISSP, TS/SCI clearance, etc. I went through that circus after I graduated with my CS degree, even with 15+ years in IT experience. A lot of interviews went like this: "Got a valid TS/SCI clearance or CISSP? No? Next in line, please." Certificates are a filter. No certs, the resume gets round-filed before it ever gets in front of a living person's eyeballs. they don't want to pay for a TS/SCI clearance they (0) Anonymous Coward | more than 2 years ago | (#39631753) they don't want to pay for a TS/SCI clearance they you to have one form some other place willing to pay for it. You can't get that on your own. Re:and how meany people are better off voc / tech (1) NotSanguine (1917456) | more than 2 years ago | (#39634229) least five year of documented experience. Any certifications that don't include one or both of these are, as I said, worthless. Re:and how meany people are better off voc / tech (1) SCHecklerX (229973) | more than 2 years ago | (#39634471) (5, Interesting) Subratik (1747672) | more than 2 years ago | (#39630617):and how meany people are better off voc / tech (2, Informative) Anonymous Coward | more than 2 years ago | (#39630777) school teaching what you want to learn. :) Re:and how meany people are better off voc / tech (2) steveb3210 (962811) | more than 2 years ago | (#39633345) If you're bright enough to do well in competent CS program, you can pick of the specifics of $solution you happen to be working on and you'll have an edge on keeping up in the long term versus those MIS kids.. Re:and how meany people are better off voc / tech (0) crazyjj (2598719) | more than 2 years ago | (#39630667) Don't worry, someone in India is not only learning it better, but willing to work for cheaper. Re:and how meany people are better off voc / tech (4, Insightful) TheRaven64 (641858) | more than 2 years ago | (#39630825):and how meany people are better off voc / tech (0) Anonymous Coward | more than 2 years ago | (#39639155) As if the H1B visa problem wasn't bad enough, most of this increase of students are foreign exchange students. Re:and how meany people are better off voc / tech (0) Anonymous Coward | more than 2 years ago | (#39631549) My company was looking to get developers on the cheap and hired an Indian on a working visa. He had one qualification that we hired him for (he had experience implementing RoHC). Now it's months after his visa expired and he went back to India (and quit working for us), and his code is finally being used in production. I have had to do two major rewrites of RoHC features already. As more profiles and features are used, I expect to have to rewrite even more of his code. This was just one experience. I work with very qualified and intelligent Indians as well, though I would recommend against hiring another one on a working visa, even if we save money. Re:and how meany people are better off voc / tech (1) Dainsanefh (2009638) | more than 2 years ago | (#39636257) That's what your company get by not being patriotic and hire American-Born. Re:and how meany people are better off voc / tech (0) Anonymous Coward | more than 2 years ago | (#39630879) and how meany people are better off voc / tech school type training then 4 years + of CS? Vocational training isn't a prerequisite for a CS degree. Besides, there are plenty of nice people in both tech school and CS majors. 10% more graduates will be disappointed (1, Interesting) sl4shd0rk (755837) | more than 2 years ago | (#39630515) Joining the other unemployed 54% * [time.com] Re:10% more graduates will be disappointed (1) I Read Good (2348294) | more than 2 years ago | (#39633109) Make sure they have interesting jobs (1) concealment (2447304) | more than 2 years ago | (#39630593) and create black holes that can only be filled by daytime television and AM talk radio. We don't want that, do we? On the other hand, if they're bored at work, they'll be prolific open source contributors! Re:Make sure they have interesting jobs (0) Anonymous Coward | more than 2 years ago | (#39630675) I am not worried about them having interesting jobs. I'm worried about them taking my job. Can we pay their professors to flunk them out? Re:Make sure they have interesting jobs (3, Interesting) dohnut (189348) | more than 2 years ago | (#396311:Make sure they have interesting jobs (1) russotto (537200) | more than 2 years ago | (#39631645) It's tough getting an embedded job unless you already have experience with the specific processor and OS the company hiring uses. Which is ridiculous, but it's one way false shortages are created. Re:Make sure they have interesting jobs (1) mlts (1038732) | more than 2 years ago | (#39631985) panels, unauthorized removal of the LP gas bottles [1], refrigerator temperature out of spec, coach not winterized and temperatures below freezing in the plumbing areas, and so on. The only practical solution would be a custom embedded monitor with a 3G radio. [1]: I'm splitting hairs, but if it is permanently mounted, it is a tank. If it is removable, it is a bottle. LP gas bottles tend to be a tempting target because they can work as anhydrous ammonia containers for meth labs. Re:Make sure they have interesting jobs (1) zildgulf (1116981) | more than 2 years ago | (#39636353) Precisely what would these CSci graduates work on? (3, Interesting) dryriver (1010635) | more than 2 years ago | (#39630657) Re:Precisely what would these CSci graduates work (1) TheRaven64 (641858) | more than 2 years ago | (#39631023) Re:Precisely what would these CSci graduates work (5, Insightful) Cajun Hell (725246) | more than 2 years ago | (#39631447):Precisely what would these CSci graduates work (1) cshay (79326) | more than 2 years ago | (#39633499) Wish I had mod points -- what a great, and positive post. Re:Precisely what would these CSci graduates work (1) zildgulf (1116981) | more than 2 years ago | (#39636417) Supply Creates Its Own Demand (2) geoffrobinson (109879) | more than 2 years ago | (#39632479) If you have a bunch of talented, smart workers around with skills, there's no shortage of things to work on. The economy isn't a zero-sum game. All these new CompSci students.... (0) Anonymous Coward | more than 2 years ago | (#39634203) They're all actually Chinese spies. Didn't you read the Slashdot article posted just a little while earlier today? [slashdot.org] Re:Precisely what would these CSci graduates work (0) Anonymous Coward | more than 2 years ago | (#39634369) Te audire no possum. Musa sapientum fixa est in aure. I can't hear you. I have a banana in my ear. yea and God said to Abraham; "You will kill your son Isaac." And Abraham said, "I can't hear You, you'll have to speak into the microphone." And God said, "I'm sorry, is this better? Check check... check. Jerry, pull the high end out, I'm still getting some hiss back here." /p Re:Precisely what would these CSci graduates work (1) Darinbob (1142669) | more than 2 years ago | (#39636453) some other embedded stuff (Facebook is not even in the running though, they're the purest of facade computing). So if you compact and contract their markets you're still get only a tiny compaction of the embedded market. The trouble is that students aren't introduced to this stuff. They see what's shoved in front of their faces, either by their peers or by Wall Street or by newspapers. They don't see the computers in their microwave, their automobile, their routers, their television, etc. Some may be away of computers in their phones but mistakenly think it's all done with Java. Some may be away of the other stuff but think it's simple stuff and not very complicated to solve. Even if only the facade exists there is a mass of complexity there that only a few people get to deal with. Video is cool, but linking to videos and editing them is boring and low tech compared to writing the codecs, optimizing the protocols, etc. Essentially the fun problem solving part of computing only gets done by a minority of programmers and engineers. The trick is to aim for that instead of the saturated job market of technicians. Don't waste your time/money (1, Insightful) crazyjj (2598719) | more than 2 years ago | (#39630759) *their employer's* money) Either way, go major in nursing if you just want money and a steady job. Re:Don't waste your time/money (2) JaredOfEuropa (526365) | more than 2 years ago | (#39635953) My anecdote (1) Anonymous Coward | more than 2 years ago | (#396309 and not going to get better anytime soon... science in the US is vastly underfunded, and now there are reams of grad students and post-docs looking for tenure-track jobs at a time when tenure is rapidly disappearing. The best case for NIH and NSF funding for next year is a 0% increase, and that's assuming the automatic debt deal budget cuts don't take effect. Time to find a new career. Re:My anecdote (0) Anonymous Coward | more than 2 years ago | (#39634215) If you want to go back to school that's great but you may be able to get a job writing code as you are right now. Some of the best developers I've ever worked with had degrees in unrelated fields. If you interview well and have a good understanding of today's programming languages and methodologies I don't see any reason why you can't start coding professionally right now. Don't go back to school just because you think you have to. If you want to, fine. If you need to, fine, but don't underestimate what you already know. Most people working in programming fields are nothing special when it comes to actual programming skills. I'm not saying you should choose a career and be mediocre at it, just that your competition probably isn't as strong as you think and I'd take a good mind over a good pedigree any day. IT Employment level now down to 1980s levels (0) Anonymous Coward | more than 2 years ago | (#39631151) If you go to the FED () and look at the labor stats IT employment has dropped every year since 2000 and is now down to 1980s levels. For the spreadsheet and "IT Glut" US Senate article you can get those at my website). The push from industry of "There aren't enough IT graduates" appears to be a reason for demanding more H-1B visas and justifying outsourcing. There is a large pool of unemployed (mostly over 50 years old) and underemployed (mostly under 30 years old) IT graduates who cannot find work. In fact IT jobs have been dropping as fast as manufacturing jobs. If you saw a headline that said we graduated 10% more sheet metal workers the response would be sorrow. As "glamorous" as IT jobs are 10% more IT graduates will mean 10% more fast food workers with IT degrees. Re:IT Employment level now down to 1980s levels (2) tjb (226873) | more than 2 years ago | (#39635703). Mini tech bubble? (0) Anonymous Coward | more than 2 years ago | (#39631347) My observation over the past few years is that, just like back in 1998-1999, everyone's fascinated with tech again. Instead of the dotcom boom, it's the Apple/smartphone/social network boom this time. We'll see what happens. I remember back in those days people were piling into CS programs and vendor certification courses alike. Some were interested, and others were out to make phat buxxx because they were "good with computers." On top of that, this time there's a generation of people who grew up with Facebook and think that's the pinnacle of modern technology. I'm on the IT side of things (engineering, not operations) and we're still working through the backlog of people who hold a vendor certification and not much else in the way of talent or troubleshooting ability. My only fear is that these mini-booms produce more of these types of individuals. I can't tell you how many times a cowboy "IT Consultant" has come in to someplace I worked at, messed things up and disappeared. Without some sort of independent yardstick, it's hard for a business to judge whether an IT person is just a good talker or whether they actually know what they're talking about. And I'm Still Having Trouble (0) PerfectionLost (1004287) | more than 2 years ago | (#39631455) And I'm still having trouble hiring a CS professional in Baltimore. I was at a local admin users group recently, and there were 3 people hiring (including myself). 2 for development, and 1 security specialist. Re:And I'm Still Having Trouble (1) Anonymous Coward | more than 2 years ago | (#39631805) Offer more money? I know what you're going to say, but the answer is, "Clearly not." That's the good news. (0) Anonymous Coward | more than 2 years ago | (#39631707) The bad news: Those fresh grads are learning Java as a first language, leaving them ill-equipped for independent thought. If their solution is not pre-built in one of the java.* or javax.* namespaces they won't be able to do it. Context of the Bubble (1) geoffrobinson (109879) | more than 2 years ago | (#39632637) some unpaid internship, consider picking up a skilled trade for a summer job. There is a good bit of demand for those types of jobs, and you never know. At the very least, you may be handy around the house when you get older. Re:Context of the Bubble (1) hackula (2596247) | more than 2 years ago | (#39633771) Be smart (0) Anonymous Coward | more than 2 years ago | (#39633213) I hope all you new graduates are smart enough to make sure you get paid nothing less than $75,000 / year. Otherwise you cheepen the industry, and sell yourself short, and piss off the rest of us already in the industry because it would lower our price. it's a good thing for computer science kids, but.. (2) bladesinger (2420944) | more than 2 years ago | (#39633261) And yet... (1) ndykman (659315) | more than 2 years ago | (#39634533) No increase in demand for teacher and professors. For those of crazy and qualified enough to teach (because we are passionate about it), we can't. I begin to see why tenure isn't necessarily a great thing. Re:And yet... (0) Anonymous Coward | more than 2 years ago | (#39635019) I begin to see why tenure isn't necessarily a great thing. Why? Professors with tenure don't teach much in this country anyway. IMHO, every time someone is tenured a teaching position ought to open up. Re:And yet... (0) Anonymous Coward | more than 2 years ago | (#39639135) Tenured = retired with full pay and benefits... what tenure? (0) Anonymous Coward | more than 2 years ago | (#39640223) Few ever reach tenure these days; they've made it far more difficult and easier for politics to prevent somebody from legitimately earning it. Meanwhile K-12 educators get it simply by not being fired for a few years. Too bad americans think computers are boring. (0) Anonymous Coward | more than 2 years ago | (#39639281) 59% of CS Masters Graduates are non resident aliens according to the survey by the same company.
http://beta.slashdot.org/story/167337
CC-MAIN-2014-41
refinedweb
6,420
66.57
Pcred, Ppriv, Psetcred, Psetpriv, Psetzoneid - get and set credentials and privileges #include <libproc.h> int Pcred(ps_prochandle_t *Pr, prcred_t *pcred, int ngroups); ssize_t Ppriv(ps_prochandle_t *Pr, prpriv_t *pprv, size_t size); int Psetcred(ps_prochandle_t *Pr, const prcred_t *pcred); int Psetpriv(ps_prochandle_t *Pr, prpriv_t *pprv); The Pr argument identifies a victim process or core file attached to the controlling process by the create and grab interfaces. For more information, see the Pcreate(3PROC) and Pgrab(3PROC) man pages. The Pcred() function retrieves the process or core file credentials which includes real, effective, and saved user IDs, real, effective, and saved group IDs, and supplementary group IDs. The ngroups argument specifies the number of supplementary group entries allocated in the cred structure of the caller. It should equal zero or one unless extra space has been allocated for the group list by the caller, like this: pcred = malloc(sizeof (prcred_t) + (ngroups - 1) * sizeof (gid_t)); The Ppriv() function retrieves the process or core file privileges. The size argument is the size in bytes of the pprv buffer of the caller. If the size argument is zero, the Ppriv() function returns the actual size needed to allocate a buffer and to call the Ppriv() function again. The Psetcred() function sets the credentials of the victim process from the correctly-constructed pcred buffer which includes the pr_ngroups member. The Psetpriv() function sets the victim process's privileges from the correctly constructed pprv buffer. On successful completion, the Pcred() function returns 0. The number of supplementary group ids for the victim is returned in the pr_ngroups member of the prcred_t structure regardless of the value of the ngroups argument. On error, it returns -1 and sets errno to indicate the error. On successful completion, the Ppriv() function returns the number of bytes read into the pprv buffer. If the size argument is zero, the Ppriv() function returns the size needed to allocate a buffer and to call the Ppriv() function again. On error, it returns -1 and sets errno to indicate the error. On successful completion, the Psetcred() and Psetpriv() functions return 0. On error, they return -1 and set errno to indicate the error. On failure, these errno values may be set: Process has been lost to control, need Preopen() Process is not stopped (Psetrun()) Signal received while waiting for stop Invalid argument The victim process has terminated See attributes(7) for descriptions of the following attributes: libproc.h(3HEAD), libproc(3LIB), Pcreate(3PROC), Pgrab(3PROC), proc(5)
https://docs.oracle.com/cd/E88353_01/html/E37847/ppriv-3proc.html
CC-MAIN-2019-43
refinedweb
412
59.84
hi guys i m working on a project for my college..where i need to store the date in this format i.e dd/mm/yyyy and time in hh/mm separatly in Oracle database ...can you help me that you i get this... Type: Posts; User: gautammuktsar@gmail.com hi guys i m working on a project for my college..where i need to store the date in this format i.e dd/mm/yyyy and time in hh/mm separatly in Oracle database ...can you help me that you i get this... hi guys i am new to J2EE . I am not getting that what is difference between the ServletRequest and HttpServletRequest ? hi sir can you provide me a best site(url) for java Thread from which i gain more .. i m new to java ... i have read many aticles on net regarding wait() and notify() but unable to get ..can you please make me understand about these two method with example public class SRDemo extends Thread { public void run() { try { for( int i = 0; i < 7; i++ ) { Thread.sleep(500); System.out.println( this.getName() + ": " + i ); } } ... hey guys can you tell is there any method in java which works similar like function gotoxy() in c++. class Bank{ int getRateOfInterest(){return 0;} } class SBI extends Bank{ int getRateOfInterest(){return 8;} } class ICICI extends Bank{ int getRateOfInterest(){return 7;} import java.util.*; class CollectionEx{ public static void main(String arg[]){ Vector obj = new Vector(); obj.add(new Integer(99)); obj.add(new Integer(78)); obj.add(66); then could be necessary for the class which implements the Iterator to provide defination for their all 3 methods ??...but while using Iterator to transverse the elements of collection(container) we... Well thank you . But one thing more in case of List interface ,class ArrayList is implementing List interface but my question is which class is implementing the Interface Iterator . i m new to java and as a matter of fact ,i m a bit confusing that how a interface contain whole methods..i have read that interface can contain only the defination of the method ..can you make me... hey guys please answer these objective question which was asked by r teachers..i m unable to get it 1. what is the reason for runtime error in java 2. what r the 3 reasons for COMPILATION ERROR... thanks :) My teacher has asked me one question that "What is difference between the final method and static method"..but i m unable to answer it properly..can you guys help me to answer it by the help of some... got it .. these are features and conventions of the upcoming Java SE 8 .. interface I1{ void show(); void display(); default void put(){ System.out.println("I am from interface I1"); } } hi i am new to java and i have not much knowledge about it.. i m not getting the way by which println() is called ...means System.out.printl()...please explain what is "out" here..
http://www.javaprogrammingforums.com/search.php?s=b791e9da05794db5b6a10a53e63b3e23&searchid=1075932
CC-MAIN-2014-41
refinedweb
501
67.96
C++ - Functional-Style Programming in C++ By David Cravey | August 2012 C++ is a multiparadigm, systems-level language that provides high-level abstractions with very low (often zero) runtime cost. The paradigms commonly associated with C++ include procedural, object-oriented and generic programming. Because C++ provides excellent tools for high-level programming, even functional-style programming is quite reasonable. By functional-style programming, I don’t mean the programming is strictly functional, just that it’s easy to use many of the functional building blocks in C++. This article will focus on one of the most important functional programming constructs: working with values as opposed to identities. I’ll discuss the strong support C++ has always had for working with values, then show how the new C++ 11 standard expands this support with lambdas. Finally, I’ll introduce a method of working with immutable data structures that maintains the speed C++ is known for while providing the protection that functional languages have long enjoyed. Values vs. Identities Let me first explain what I mean by working with values rather than identities. Simple values such as 1, 2 and 3 are easy to identify. I could also say that 1, 2 and 3 are constant integer values. This would be redundant, however, because all values are actually constants and the values themselves never change (that is, 1 is always 1 and 1 will never be 2). On the other hand, the value associated with an identity may change (x might equal 1 now, but it could equal 2 later). Unfortunately, it’s easy to confuse values and value types. Value types are passed around by value rather than by reference. Though I want to focus here on the values and not the mechanism involved in using or copying them, it’s useful to see how value types go part way in preserving the concept of values versus identities. The code in Figure 1 demonstrates a simple use of a value type. void Foo() { for (int x = 0; x < 10; ++x) { // Call Bar, passing the value of x and not the identity Bar(x); } } void Bar(int y) { // Display the value of y cout << y << " "; // Change the value that the identity y refers to // Note: This will not affect the value that the variable x refers to y = y + 1; } // Outputs: // 0 1 2 3 4 5 6 7 8 9 With only a small change, the variable y can become a reference type—which drastically changes the relationship between x and y, as shown in Figure 2. As Figure 3 shows, C++ also provides the const modifier, which prevents the programmer from making changes to a variable and thus further preserves the concept of a value. (As with most things in C++, however, there’s at least one way to defeat that protection. For more information, look up const_cast, which is intended for working with older code that isn’t “const correct.”) void Foo() { for (int x = 0; x < 10; ++x) { // Call Bar, passing the identity of x, // yet the value of x will be protected by the const Bar(x); } } void Bar(const int& y) { // Use the value of y cout << y << " "; // Attempt to change the value of what the identity y refers to y = y + 1; // This line will not compile because y is const! } Note in Figure 3 that though y is passed by reference, the value of y is protected at compile time by a const modifier. This gives C++ programmers an efficient method of passing large objects while working with their values as opposed to their identities. With the const modifier, C++ has immutable data types that resemble those found in most functional programming languages. However, dealing with these immutable data types is difficult. Furthermore, making deep (full) copies of large objects for every small change isn’t efficient. Nonetheless, it should be clear that standard C++ has always had a concept of working with values (even if it’s not a very pure concept). Note that the support for value types extends to user-defined types through copy constructors and assignment operators. C++ copy constructors and assignment operators allow user-defined types to make a deep copy of the object. Keep in mind that while C++ copy constructors can be implemented to make a shallow copy, you’ll have to make sure the value semantics are preserved. C++ 11 Support for Functional-Style Programming C++ 11 brings a number of new tools for functional-style programming. Perhaps most important, C++ now has support for lambdas (also known as closures or anonymous functions). Lambdas allow you to compose your code in ways that wouldn’t have been practical before. This functionality was previously available through functors, which are powerful but less practical to use. (Actually, C++ lambdas write anonymous functors behind the scenes.) Figure 4 shows how lambdas have improved our code with a simple example that uses the C++ standard library (STL). In this case, the for_each function applies a lambda to each element of a vector. It’s important to note that C++ lambdas have been designed to be used inline when possible; thus lambdas can run as fast as handcrafted code. While C++ is just one of the many imperative languages that now have lambdas, what makes C++ lambdas special is that (similar to functional programming languages) they can preserve the concept of working with values as opposed to identities. While functional programming languages accomplish this by making variables immutable, C++ does it by providing control over the capture. Consider the code in Figure 5. void Foo() { int a[3] = { 11, 12, 13 }; vector<function<void(void)>> vf; // Store lambdas to print each element of an array int ctr; for (ctr = 0; ctr < 3; ++ctr) { vf.push_back([&]() { cout << "a[" << ctr << "] = " << a[ctr] << endl; }); } // Run each lambda for_each(begin(vf), end(vf), [](function<void(void)> f) { f(); }); } // Outputs: // a[3] = -858993460 // a[3] = -858993460 // a[3] = -858993460 In this code, everything is captured by reference, which is the standard behavior for lambdas in other languages. Yet capturing by reference complicates things unless the variables being captured are immutable. If you’re new to working with lambdas, you probably expect the following output from the code: However, that’s not the output you get—and the program might even crash. This is because the variable ctr is captured by reference, so all of the lambdas use the final value of ctr (that is, 3, the value that made the for loop come to an end) and then access the array beyond its bounds. It’s also worth noting that to keep the ctr variable alive to be used by the lambda outside of the for loop, the ctr variable’s declaration has to be lifted out of the for loop. While some languages eliminate the need to lift value type variables to an appropriate scope, that doesn’t really solve the problem, which is that the lambda needs to use the value of ctr as opposed to the identity of the variable ctr. (There are workarounds for other languages that involve making an explicit copy to a temporary variable. However, this makes it a bit unclear as to what’s going on, and it’s error-prone because the original variable is also captured and thus is still available for use.) As Figure 6 shows, C++ provides a simple syntax to allow easy control of the lambda’s capture, which preserves the concept of working with values. Figure 6 C++ Syntax for Controlling Lambda Capture It’s clear from Figure 6 that the programmer has complete control over how the lambda captures variables and values. However, while this preserves the concept of working with values, it does nothing to make working with complex data structures as values efficient. Immutable Data Types What’s missing are the efficient immutable data structures that some functional programming languages have. These languages facilitate immutable data structures that are efficient even when very large because they share common data. Creating data structures in C++ that share data is trivial—you just dynamically allocate data and each data structure has pointers to the data. Unfortunately, it’s more difficult to manage the lifetime of shared variables (for this reason, garbage collectors have become popular). Luckily, C++ 11 provides an elegant solution for working with shared variables through the std::shared_ptr template class, as shown in Figure 7. void Foo() { // Create a shared int // (dynamically allocates an integer // and provides automatic reference counting) auto sharedInt = make_shared<int>(123); // Share the integer with a secondShare // (increments the reference count) shared_ptr<int> secondShare(sharedInt); // Release the pointer to the first integer // (decrements the reference count) sharedInt = nullptr; // Verify the shared int is still alive cout << "secondShare = " << *secondShare << endl; // Shared int is automatically de-allocated // as secondShare falls out of scope and the reference // count falls to zero } // Outputs: // secondShare = 123 The code in Figure 7 illustrates a simple use of std::shared_ptr and its helper function std::make_shared. Using std::shared_ptr makes it easy to share data among data structures without fear of leaking memory (as long as circular references are avoided). Note that std::shared_ptr provides the basic thread-safety guarantees, and runs fast because it uses a lock-free design. However, keep in mind that the basic thread-safety guarantee that std::shared_ptr provides doesn’t automatically extend to the object to which it’s pointing. Still, std::shared_ptr guarantees it will not reduce the thread-safety guarantee of the object it points to. Immutable objects inherently provide a strong thread-safety guarantee because once they’re created they never change. (Actually, they never change in an observable manner, which includes, among other things, an appropriate thread-safety guarantee.) Therefore, when you use a std::shared_ptr with an immutable object, the combination maintains the immutable object’s strong thread-safety guarantee. I can now easily create a simple immutable class that potentially shares data, as shown in Figure 8. class Immutable { private: // Use a normal double, copying is cheap double d_; // Use a shared string, because strings can be very large std::shared_ptr<std::string const> s_; public: // Default constructor Immutable() : d_(0.0), s_(std::make_shared<std::string const>("")) {} // Constructor taking a string Immutable(const double d, const string& s) : d_(d), s_(std::make_shared<std::string const>(s)) {} // Move constructor Immutable(Immutable&& other) : s_() { using std::swap; swap(d_, other.d_); swap(s_, other.s_); } // Move assignment operator Immutable& operator=(Immutable&& other) { swap(d_, other.d_); swap(s_, other.s_); return *this; } // Use default copy constructor and assignment operator // Getter Functions double GetD() const { // Return a copy because double is small (8 bytes) return d_; } const std::string& GetS() const { // Return a const reference because string can be very large return *s_; } // "Setter" Functions (always return a new object) Immutable SetD(double d) const { Immutable newObject(*this); newObject.d_ = d; return newObject; } Immutable SetS(const std::string& s) const { Immutable newObject(*this); newObject.s_ = std::make_shared<std::string const>(s); return newObject; } }; The code in Figure 8 is a bit long, but most of it is boilerplate code for the constructors and assignment operators. The last two functions are the key to making the object immutable. Note that the SetS and SetD methods return a new object, which leaves the original object unchanged. (While including the SetS and SetD methods as members is convenient, it’s a bit of a lie, because they don’t actually change the original object. For a cleaner solution, see the ImmutableVector in Figures 9 and 10.) Figure 11 shows the Immutable class in action. template <class ImmutableVector> void DisplayImmutableVector(const char* name, const ImmutableVector& v) { using namespace std; cout << name << ".Size() = " << v.Size() << ", " << name << "[] = { "; for (size_t ctr = 0; ctr < v.Size(); ++ctr) { cout << v[ctr] << " "; } cout << "}" << endl; } void ImmutableVectorTest1() { // Create an ImmutableVector with a branching size of four ImmutableVector<int, 4> v; // Another ImmutableVector (we will take a copy of v at element 6) ImmutableVector<int, 4> aCopyOfV; // Push 16 values into the vector (this will create a two level tree). // Note that the vector is being assigned to itself. The // move constructor insures this is not very expensive, but // if a copy was made at any point the copy would remain // unchanged, but continue to share the applicable data with // the current version. for (int ctr = 0; ctr < 10; ++ctr) { v = AppendValue(v, ctr); if (ctr == 6) aCopyOfV = v; } // Display the contents of the vectors DisplayImmutableVector("v", v); DisplayImmutableVector("aCopyOfV", aCopyOfV); } // Outputs: // v.Size() = 10, v[] = { 0 1 2 3 4 5 6 7 8 9 } // aCopyOfV.Size() = 7, aCopyOfV[] = { 0 1 2 3 4 5 6 } void ImmutableVectorTest2() { ImmutableVector<int, 4> v; v = AppendValue(v, 1); v = AppendValue(v, 2); v = AppendValue(v, 3); int oldValue = v.Back(); auto v1 = TruncateValue(v); auto v2 = SubstituteValueAtIndex(v, 0, 3); auto v3 = GenerateFrom(v, [](ImmutableVector<int, 4>::MutableVector& v) { v[0] = 4; v[1] = 5; v[2] = 6; v.PushBack(7); v.PushBack(8); }); auto v4 = GenerateFrom(v3, [](ImmutableVector<int, 4>::MutableVector& v4) { using namespace std; cout << "Change v4 by calling PopBack:" << endl; cout << "x = v4.PopBack()" << endl; int x = v4.PopBack(); cout << "x == " << x << endl; cout << endl; }); // Display the contents of the vectors DisplayImmutableVector("v", v); DisplayImmutableVector("v1", v1); DisplayImmutableVector("v2", v2); DisplayImmutableVector("v3", v3); DisplayImmutableVector("v4", v4); } // Outputs: // Change v4 by calling PopBack: // x = v4.PopBack() // x == 8 // // Resulting ImmutableVectors: // v.Size() = 3, v[] = { 1 2 3 } // v1.Size() = 2, v1[] = { 1 2 } // v2.Size() = 3, v2[] = { 3 2 1 } // v3.Size() = 5, v3[] = { 4 5 6 7 8 } // v4.Size() = 4, v4[] = { 4 5 6 7 } using namespace std; void Foo() { // Create an immutable object double d1 = 1.1; string s1 = "Hello World"; Immutable a(d1, s1); // Create a copy of the immutable object, share the data Immutable b(a); // Create a new immutable object // by changing an existing immutable object // (Note the new object is returned) string s2 = "Hello Other"; Immutable c = a.SetS(s2); // Display the contents of each object cout << "a.GetD() = " << a.GetD() << ", " << "a.GetS() = " << a.GetS() << " [address = " << &(a.GetS()) << "]" << endl; cout << "b.GetD() = " << b.GetD() << ", " << "b.GetS() = " << b.GetS() << " [address = " << &(b.GetS()) << "]" << endl; cout << "c.GetD() = " << c.GetD() << ", " << "c.GetS() = " << c.GetS() << " [address = " << &(c.GetS()) << "]" << endl; } // Outputs: // a.GetD() = 1.1, a.GetS() = Hello World [address = 008354BC] // b.GetD() = 1.1, b.GetS() = Hello World [address = 008354BC] // c.GetD() = 1.1, c.GetS() = Hello Other [address = 008355B4] Note that object b shares the same string as object a (both strings are at the same address). Adding additional fields with associated getters and setters is trivial. Though this code is good, it’s a little more difficult to scale to containers when you’re being efficient. For example, a naïve ImmutableVector might maintain a list of shared pointers representing each element of the array. When the naïve Immutable-Vector is changed, the entire array of shared pointers would need to be duplicated, incurring additional cost as each shared_ptr element of the array would need its reference count to be incremented. There is a technique, though, that allows the data structure to share most of its data and minimize the duplication. This technique uses a tree of some form to require duplication of only the nodes that are directly affected by a change. Figure 12shows a comparison of a naïve ImmutableVector and a smart ImmutableVector. Figure 12 Comparing Naïve and Smart ImmutableVectors This tree technique scales nicely: as the number of elements grows, the percent of the tree that needs to be duplicated is minimized. Moreover, by adjusting the branching factor (so each node has more than two children), you can achieve a balance in memory overhead and node reuse. I developed a smart ImmutableVector template class that can be downloaded from archive.msdn.microsoft.com/mag201208CPP. Figure 9 shows how you can use my ImmutableVector class. (As previously noted, to make the immutable nature of the ImmutableVector clearer to the users, ImmutableVector uses static member functions for all actions that generate new versions.) For read-only actions, the vector can be used much like a regular vector. (Note that for this example I haven’t implemented iterators, but doing so should be fairly trivial.) For write actions, the AppendValue and TruncateValue static methods return a new ImmutableVector, thus preserving the original object. Unfortu-nately, this isn’t reasonable for the array subscript operator, so I made the array subscript operator read-only (that is, it returns a const reference) and provided a SubstituteValueAtIndex static method. It would be nice, however, to be able to make a large number of modifications using the array subscript operator in a single block of code. To facilitate this, ImmutableVector provides a GenerateFrom static method, which takes a lambda (or any other functor). The lambda in turn takes a reference to MutableVector as a parameter, which allows the lambda to work on a temporary MutableVector that can be changed freely like a normal std::vector. The example in Figure 10 shows the various methods for operating on the ImmutableVector. The beauty of the GenerateFrom static method is that the code within it can be written in an imperative way, while resulting in an immutable object that can be safely shared. Note that the Generate-From static method prevents unauthorized access to the underlying ImmutableVector by disabling the MutableVector it passed into the lambda as soon as the lambda exited. Please note as well that while ImmutableVector provides a strong thread-safety guarantee, its helper class MutableVector does not (and is intended to be only used locally within the lambda, not passed around to other threads). My implementation also optimizes for multiple changes within the Change method such that there’s minimal restructuring occurring on the temporary tree, which gives a nice performance boost. Wrapping Up This article gives you just a taste of how you can use functional-style programming in your C++ code. Moreover, C++ 11 features such as lambdas bring a touch of functional-style programming regardless of the paradigm used. David Cravey is a Visual C++ MVP who enjoys programming in C++ maybe a bit too much. You’ll find him presenting at local C++ user groups and universities. During the day he enjoys working at NCR, through TEKsystems in Fort Worth, Texas. Thanks to the following technical experts for reviewing this article: Giovanni Dicanio, Stephan T. Lavavej, Angel Hernández Matos, Alf P. Steinbach and David Wilkinson Receive the MSDN Flash e-mail newsletter every other week, with news and information personalized to your interests and areas of focus.
https://msdn.microsoft.com/en-us/magazine/jj553512.aspx
CC-MAIN-2019-43
refinedweb
3,100
50.67
Python3 has a multiprocessing module that provides an API that’s similar to the one found in the threading module. The main selling point behind multiprocessing over threading is that multiprocessing allows tasks to run in a truly concurrent fashion by spanning multiple CPU cores while threading is still limited by the global interpreter lock (GIL). The Process class found in multiprocessing works internally by spawning new processes and providing classes that allow for data sharing between processes. Since multiprocessing uses processes rather than threads, child processes do not share their memory with the parent process. That means we have to rely on low-level objects such as pipes to allow the processes to communicate with each other. The multiprocessing module provides high level classes similar to the ones found in threading that allow for sharing data between processes. This example demonstrates the producer consumer pattern using processes and the Queue class sharing data. Code import time import os import random from multiprocessing import Process, Queue, Lock # Producer function that places data on the Queue def producer(queue, lock, names): # Synchronize access to the console with lock: print('Starting producer => {}'.format(os.getpid())) # Place our names on the Queue for name in names: time.sleep(random.randint(0, 10)) queue.put(name) # Synchronize access to the console with lock: print('Producer {} exiting...'.format(os.getpid())) # The consumer function takes data off of the Queue def consumer(queue, lock): # Synchronize access to the console with lock: print('Starting consumer => {}'.format(os.getpid())) # Run indefinitely while True: time.sleep(random.randint(0, 10)) # If the queue is empty, queue.get() will block until the queue has data name = queue.get() # Synchronize access to the console with lock: print('{} got {}'.format(os.getpid(), name)) if __name__ == '__main__': # Some lists with our favorite characters names = [['Master Shake', 'Meatwad', 'Frylock', 'Carl'], ['Early', 'Rusty', 'Sheriff', 'Granny', 'Lil'], ['Rick', 'Morty', 'Jerry', 'Summer', 'Beth']] # Create the Queue object queue = Queue() # Create a lock object to synchronize resource access lock = Lock() producers = [] consumers = [] for n in names: # Create our producer processes by passing the producer function and it's arguments producers.append(Process(target=producer, args=(queue, lock, n))) # Create consumer processes for i in range(len(names) * 2): p = Process(target=consumer, args=(queue, lock)) #...') Explanation The program demonstrates the producer and consumer pattern. We have two functions that run in their own independent processes. The producer function places supplied names on the Queue. The consumer function monitors the Queue and removes names from it as they become available. The producer function takes three objects: a Queue, a Lock, and a List of names. It start with acquiring a lock on the console. The console is still a shared resource so we need to make sure only one Process writes to the console at a time or they will write over the top of one another. After acquiring a lock on the console, the function prints out its process id (PID). The producer function enters a for each loop on lines 14-16. It sleeps between 0-10 seconds on line 15 to simulate a delay in processing and then it places a name on the Queue on line 16. When the for each loop is complete, the function aquires another console lock and then notifies the user it is exiting. At this point, the process ends. The consumer function runs in it’s own process as well. It takes the Queue and the Lock as it’s parameters and then acquires a lock on the console to notify the user it is starting. The consumer prints out it’s PID also. Next the consumer enters an infinte loop on lines 30-38. It similuates sleeping on line 31 and then makes a call the queue.get() on line 34. If the queue has data, the get() method returns that data immediately and the consumer prints the data on line 38. Otherwise, get() blocks execution until data is available. Line 41 is the entry point to the programing, using the if __name__ == ‘__main__’ test. We begin on 44 by making a list of names. The Queue object is created on line 49 and the Lock() object is made on line 52. Then on lines 57-59, we enter a for-each loop and create our producer Process objects. We use the target parameter to point the Process at the producer function and then pass in a tuple for the arguments that the function is called with. Creating the consumers processes has one extra that that isn’t needed when creating the Producers. Lines 62-68 creates the consumer processes, but on line 67, set the daemon property to True. This is needed because the consumer function uses and infinite loop and those processes will never terminate unless they are marked as daemon processes. Once are processes are created, we start them by calling start() on each Process object (lines 72-76). Like threads, Processes also have a join() method that can be used to synchronize a program. Our consumer processes never return, so calling join() on them would cause the program to hang, but our producer processes do return so we use join() on line 80 to cause the parent process to wait for the producer processes to exit. Resources Lutz, Mark. Programming Python. Beijing, OReilly, 2013. Programming Python: Powerful Object-Oriented Programming
https://stonesoupprogramming.com/tag/concurrency/
CC-MAIN-2021-31
refinedweb
895
63.49
{-| This module provides the tutorial for "Control.Frame". -} module Control.Frame.Tutorial ( -- * Restricted Monads -- $restrict1 -- $extension -- $restrict2 -- * Type Signatures -- $types -- * Prompt Finalization -- $prompt -- * Composition -- $compose -- * Finalization -- $ensure -- * Folds -- $fold -- * Strictness -- $strict -- * Robustness -- $robust ) where -- For documentation import Control.Category import Control.Frame import Control.IMonad import Control.IMonad.Trans import Control.Monad.Trans.Class import Control.Pipe hiding (await, yield, Await, Yield) {- $restrict1 'Frame's extend 'Pipe's with two new features: * Folding input and intercepting upstream termination * Guaranteeing prompt and deterministic finalization However, these extra features comes with some added complexity: restricted monads, also known as indexed monads. Restricted monads sound scarier than they are, so I'll demonstrate that if you are comfortable using monads, then you'll be comfortable using restricted monads. Let's translate the @take'@ function from the 'Pipe's tutorial into a 'Frame' to see what changes when we use restricted monads: -} -- $extension -- > {-# LANGUAGE RebindableSyntax #-} -- > -- > import Control.Frame -- > import Control.IMonad.Do -- > import Control.IMonad.Trans -- > import Prelude hiding (Monad(..)) -- > -- > take' :: Int -> Frame a IO (M a) C () -- > take' n = do -- > replicateMR_ n $ do -- > x <- await -- > yield x -- > close -- > liftU $ putStrLn "You shall not pass!" {- $restrict2 This time I included all imports and highlighted the new @RebindableSyntax@ extension. The new imports belong to the @Control.IMonad@ hierarchy from the @index-core@ package, which provides the core restricted monad functionality. Yet, you almost wouldn't even know you were using an restricted monad just by looking at the code. This is because @index-core@ can rebind @do@ notation to use restricted monads instead of ordinary extensions. Three things make this possible: * The @RebindableSyntax@ extension, which allows libraries to override @do@ syntax (among other things) * The @Control.IMonad.Do@ module which exports the new bindings for @do@ notation * Hiding 'Monad' from the Prelude so that it does not conflict with the bindings from @index-core@ However, you are not obligated to rebind @do@ notation to use 'Frame's. You can choose to keep ordinary @do@ notation and desugar the restricted monad by hand. Just import @Control.IMonad@ instead, drop the @RebindableSyntax@ extension, and don't hide 'Monad'. Then you can desugar @take'@ manually using the restricted monad operators: > import Control.Frame > import Control.IMonad > import Control.IMonad.Trans > > take' :: Int -> Frame a IO (M a) C () > take' n = > (replicateMR_ n $ > await !>= \x -> > yield x) !>= \_ -> > close !>= \_ -> > liftU $ putStrLn "You shall not pass!" However, for this tutorial I will use the @do@ notation, since it's prettier and easier to use. You'll also notice functions that resemble the ones in @Control.Monad@, except with an \'@R@\' suffix on the end of them, like 'replicateMR_'. Most functions in @Control.Monad@ have a restricted counterpart provided by @Control.IMonad.Restrict@ (which is in turn re-exported by @Control.IMonad@), such as 'whenR', 'foreverR', and 'mapMR'. Also, every time you lift an operation from the base monad, you must use 'liftU' instead of 'lift'. 'Frame's are \"restricted monad transformers\", and they would normally lift a base restricted monad using 'liftI', but they can also lift ordinary monads, too, using 'liftU' (mnemonic: \"lift\" an ordinary monad and \'U\'pgrade it to a restricted monad). -} {- $types The 'Frame' type constructor also looks a bit different, too: > Frame a IO (M a) C () Let's dissect that to understand how 'Frame's work: > | Output | Base monad | Initial Input | Final Input | Return Value > Frame a IO (M a) C () 'Frame's differ from 'Pipe's in that their input end indexes the beginning and end of the operation. Our @take'@ function starts off with an open input end (@M a@), and ends with a closed input end (@C@). @take'@ finishes with a closed input end because it called the 'close' function, which seals off and finalizes upstream. You can see that the 'close' primitive changes the index just by looking at its type: > close :: Monad m => Frame b m (M a) C () The 'close' instruction begins with an open input end (@M a@) and finishes with a closed input end (@C@). If you tried to call 'close' twice, you'd get a type error: > -- wrong! > do close > close This prevents you from accidentally finalizing upstream twice. 'close' is the only primitive that changes the index, and there is no way to reopen the input once you have closed it. 'close' also forbids you from 'await'ing input from upstream after you have already closed it. If you try, you will get a type error > -- wrong! > do close > await This prevents you from requesting input from a finalized pipe. In fact, once you 'close' your input end, every upstream 'Frame' disappears completely. You couldn't get input from upstream anyway, even if you somehow allowed 'await' statements after 'close'. You can check out 'await''s type signature to see why it won't type-check after 'close': > await :: Monad m => Frame b m (M a) (M a) a 'await' must begin with the input end open (@M a@) and it leaves the input end open when done (@M a@). However, you can still use a 'yield' anywhere: > yield :: Monad m => b -> Frame b m i i () 'yield' will work whether or not the input end is open, and it leaves the input end in the same state once 'yield' is done. -} {- $prompt Every 'Frame' must close its input end /exactly/ one time before you can compose it with other 'Frame's. The only exception is if a 'Frame' never terminates: > -- This type-checks because foreverR is polymorphic in the final index > printer :: (Show b) => Frame C IO (M b) C r > printer = foreverR $ do > a <- await > liftU $ print a However, when a 'Frame' no longer needs input then you should 'close' it as early as possible. The earlier you 'close' upstream, the more promptly upstream gets finalized. If you write a stand-alone producer from start to finish, you can be sure it will never need upstream, so you can close it immediately: > -- I'm keeping fromList's input end polymorphic for a later example > fromList :: (M.Monad m) => [b] -> Frame b m (M a) C () > fromList xs = do > close > mapMR_ yield xs However, if @fromList@ were a library function, you would remove the 'close' statement as you cannot guarantee that your user won't want to 'await' after @fromList@. Or, the user might want to call @fromList@ twice within the same 'Frame', and having two close statements would lead to a type error. Therefore, a good rule of thumb when writing library code for 'Frame's is to always let the user decide when to 'close' the 'Frame' unless you are writing a stand-alone 'Frame'. So for right now, I will leave the 'close' in @fromList@ for simplicity and treat it as a stand-alone 'Frame'. Also, it will come in handy for a later example. -} {- $compose Composition works just like 'Pipe's, except you use the ('<-<') composition operator instead of ('<+<'): > stack :: Stack IO () > stack = printer <-< take' 3 <-< fromList [1..] The 'Frame' equivalent to 'Pipeline' is a 'Stack' (mnemonic: call stack; also the name 'Frame' refers to a call stack frame): > type Stack m r = Frame C m (M ()) C r Similarly, you use 'runFrame' instead of 'runPipe' to convert the 'Frame' back to the base monad: >>> runFrame stack 1 2 3 You shall not pass! However, let's carefully inspect the type of composition: > (<-<) :: Monad m > => Frame c m (M b) C r > -> Frame b m (M a) C r > -> Frame c m (M a) C r Each argument 'Frame' must begin in an open state and end in a closed state. This means that each 'Frame' in a 'Stack' must call 'close' exactly once before it may be used. 'runFrame' has the exact same restriction: > runFrame :: Monad m => Stack m r -> m r > runFrame ~ Monad m => Frame C m (M ()) C r -> m r Composition specifically requires the user to define when to finalize upstream and does not assume this occurs at the end of the 'Frame'. This doesn't pose a problem for stand-alone 'Frame's, since they will know when they no longer need input, but smaller library components designed to be assembled into larger 'Frame's should let the user decide at the very last moment where to 'close' the 'Pipe'. There is no way to know ahead of time where the 'close' should be until the complete 'Frame' has been assembled. -} {- $ensure With 'Frame's in hand, we can now write a safe @read'@ function: > readFile' :: Handle -> Frame Text IO C C () > readFile' h = do > eof <- liftU $ hIsEOF h > whenR (not eof) $ do > s <- liftU $ hGetLine h > yield s > readFile' h > > read' :: FilePath -> Frame Text IO C C () > read' file = do > liftU $ putStrLn "Opening file..." > h <- liftU $ openFile file ReadMode > -- The following requires "import qualified Control.Monad as M" > finallyD (putStrLn "Closing file ..." M.>> hClose h) $ readFile' h The 'finallyD' function registers a block-level finalizer that executes if a downstream 'Pipe' terminates or if the block completes normally. The more general 'finallyF' function will call the finalizer if /any/ 'Frame' terminates. Usually you would always want to use 'finallyF', but because of some type limitations you can only use 'finallyD' after a 'Frame' is closed. A future release of this library will fix this and merge 'finallyD' into 'finallyF'. So that means that for everything beginning before a 'close' statement, use 'finallyF', otherwise use 'finallyD'. Similarly, you can use the 'catchF' / 'catchD' counterparts to the \"finally\" functions. The \"catch\" functions run the finalizer only if another 'Frame' terminates before the block is done, but not if the block terminates normally. We don't 'close' the @read'@ function because it's not a stand-alone 'Frame'. We want to be able to concatenate multiple @read'@s together within the same 'Frame', like so: > files = do > close > read' "file1.txt" > read' "file2.txt" So let's assume those two files have the following contents: \"@file1.txt@\" > Line 1 > Line 2 > Line 3 \"@file2.txt@\" > A > B > C We can now check to see if our @files@ producer works: >>> runFrame $ printer <-< files Opening file... "Line1" "Line2" "Line3" Closing file ... Opening file... "A" "B" "C" Closing file ... More importantly, files are never opened if they aren't demanded and they are always properly finalized if the consumer terminates early: >>> runFrame $ printer <-< take' 2 <-< files Opening file... "Line1" "Line2" Closing file ... You shall not pass! So we get lazy, deterministic, and prompt resource management. Nice! -} {- $fold 'Frame's can actually do more than just manage finalization! Using 'Frame's, we can now correctly implement folds like @toList@ in a way that is truly compositional: > toList :: (M.Monad m) => Frame b m (M a) (M a) [a] > toList = do > a' <- awaitF > case a' of > Nothing -> return [] > Just a -> do > as <- toList > return (a:as) We used one new function this time: 'awaitF'. This is like 'await' except that it returns a 'Nothing' if upstream terminates before 'yield'ing back a value. This allows you to intercept upstream termination and do some cleanup, and in our case we use it to end the fold. You only receive a 'Nothing' once when you use 'awaitF'. Any attempt to request more input after you receive the first 'Nothing' will terminate the current 'Frame' using the upstream return value. In fact, 'await' is built on top of 'awaitF': > await = do > a' <- awaitF > case a' of > Nothing -> await > Just a -> return a If it gets a 'Nothing', it just ignores it and 'await's again, choosing to not do any cleanup. Now let's make sure our @toList@ function works. I didn't make @toList@ a stand-alone 'Frame', so we will have to include a 'close' statement to complete it before composing it: > p1 = do > xs <- toList > close > return (Just xs) > > p2 xs = do > fromList xs > return Nothing -- Remember: they need the same return type >>> runFrame $ p1 <-< p2 [1..10] Just [1,2,3,4,5,6,7,8,9,10] -} {- $strict Lazy resource management has one important disadvantage: we can't free the resource until downstream no longer needs input. Many libraries duplicate their code to provide Lazy and Strict versions, allowing the user to decide if they want: * Lazy input, which conserves memory, but holds onto the resource until downstream is done processing it * Strict input, which loads everything into memory, but can then immediately dispose of the resource before the input is processed What if there were a way to seamlessly switch between those semantics or even choose something in between? Well, it turns out we can! First, we can combine @fromList@ and @toList@ into something even cooler: > strict :: (M.Monad m) => Frame a m (M a) C () > strict = do > xs <- toList > fromList xs As the name suggests, the @strict@ function is strict in its input. @strict@ loads the entire input into memory, finalizes upstream, then proceeds to hand the input off to downstream. We can prove this just by using it: >>> runFrame $ printer <-< strict <-< files > Opening file... > Closing file ... > Opening file... > Closing file ... > "Line1" > "Line2" > "Line3" > "A" > "B" > "C" Both files were disposed of immediately, at the expense of using more memory. But what if we want something in between strictness and laziness? Maybe something like this: >>> runFrame $ printer <-< strict <-< take' 2 <-< files Opening file... Closing file ... You shall not pass! "Line1" "Line2" Now we have the best of both worlds. We can pick and choose how much of our source to strictly load into memory. In the above example, we specified that we wanted to be strict only in the first two lines of our input, and as a result the third line of \"@file1.txt@\" is never read and \"@file2.txt@\" is never even opened! Now we have a way to seamlessly slide anywhere on the spectrum between laziness and strictness, and it's all implemented entirely within Haskell in a way that is elegant and intuitive without the use of artificial and clumsy 'seq' annotations. -} {- $robust The 'Frame' implementation exposes all internals, yet this does not compromise safety or invariants in any way. The library's implementation is \"correct-by-construction\", meaning that you can extend it with your own features if you so choose, and you never have to worry about accidentally breaking any laws, such as the associativity of composition. This has the following important practical benefits for finalization and folds: * Finalizers never get duplicated or dropped * Folds can be performed anywhere within the 'Stack', not just at the most downstream 'Frame', as the @strict@ example illustrates. * You can reason about each 'Frame's finalization behavior completely independently of other 'Frame's. Composition elegantly handles every single corner case. This directly follows from strictly enforcing the 'Category' laws, because categories have no corners! -}
http://hackage.haskell.org/package/pipes-2.4.0/docs/src/Control-Frame-Tutorial.html
CC-MAIN-2015-35
refinedweb
2,450
60.85