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 |
|---|---|---|---|---|---|
Installing Objective-C Compiler
Setup the Compiler
Objective-C is a strict superset of C; the additional functionality is obtained by linking to the Objective-C library when building using the standard GNU GCC Compiler. This makes setting up a new compiler very simple, as we can make a copy of the standard compiler and change the linker settings.
Caution: Make sure your GNU GCC Compiler is properly setup before attempting to setup for Objective-C
1) Go to Settings->Compiler and debugger...
2) Select GNU GCC Compiler and make a copy it; name it whatever you like, but "GNU GCC Obj-C Compiler" would be the most descriptive.
3) Under Linker Settings, add -lobjc to Other linker options; you don't need to explicitly add the libobjc.a library, as the flag tells gcc to include it for us.
Adding Filetype Support
1) Go to Settings->Environment...
2) Select Files extension handling and add *.m
3) Go to Project->Project tree->Edit file types & categories...
4) Under Sources, add *.m to the list of filetypes.
Proper Syntax Highlighting
1) Go to Settings->Editor...
2) Select Syntax highlighting and go to Filemasks.... Add *.m to the list of filetypes.
3) Go to Keywords... (next to Filemasks...) and create a new set (up arrow). Add this to the Keywords: box:
Keywords
@interface @implementation @end @class @selector @protocol @public @protected @private id BOOL YES NO SEL nil NULL self
Note: if you feel so inclined, you could create a new custom lexer.
Optional Changes
1) Go to Settings->Compiler and dubugger...
2) Under Other Settings, change Compiler logging to Full command line. If ObjC still refuses to build properly for you, you can use this to compare the command line arguments C::B uses against the commands you would use if you were building the program manually on the command line.
3) Under Other Settings, go to Advanced Options. For Link object files to executable and Link object files to console executable, move -o $exe_output to the end of the macros. For reasons beyond my understanding, GCC will sometimes (albeit rarely) complain during complex builds if this isn't the last argument on the line.
Important Notes
1) By default, C::B will select CPP as the default compiler variable for a new source file, and the file will not be compiled or linked to a target. Whenever you add or create a new ObjC source (*.m) in your project, you must right-click on it and go to Properties.... Under advanced, change the compiler variable to CC. Under Build, select both Compile file and Link file. Before you close the dialog, go to General and uncheck File is read-only. This will automatically get selected when you change the other options and if you close the dialog before you uncheck it, you'll have to go back and change it, then close and reopen the file in the viewer before you can edit it.
2) When you add a header file (*.h), you'll also need to open up its properties window and change the compiler variable to CC. You don't need to do anything else to it.
Troubleshooting
There's a small handful of pitfalls you can fall into when attempting to compile Objective-C applications using TDM-GCC or MinGW, and these pitfalls are unfortunately not well documented. This section tries to identify and solve the currently identified issues; note that these are issues as of the current GCC 4.5.x branch, unless otherwise noted. There is currently no 4.6.x port of GCC for TDM-GCC/MinGW available; the GCC 4.6.x branch introduces an entirely new Objective-C library that brings the ObjC implementation inline with Apple's own implementation of the library. Many of these issues are likely solved in this newest release.
There has been some trouble with the -lobjc flag trying to link to libobjc.dll.a, which has been a nonfunctional shared library for some time. If this shared library is not removed before compilation, gcc will throw undefined reference to ... errors at every ObjC method or library call during the linking stage. This shared library must be removed, and in the case of TDM-GCC, is located at: [mingw install directory]/lib/gcc/[tdm install type]/[version]/libobjc.dll.a. If you've installed TDM-GCC x64, you must also remove the 32-bit copy of the shared library, located at: ...[version]/32/libobjc.dll.a.
BOOL Redefined
I haven't experienced this error as of TDM-GCC 4.5.2, but on TDM-GCC 4.5.1 and earlier, attempts to build a 32-bit ObjC application that also imports <windows.h> would produce a BOOL redefined error. This is the result of the windows headers defining their own version of BOOL; the headers do make checks to see if ObjC is being used (by checking if __OBJC__ is defined) and change various types and declarations to make themselves compatible, but the ObjC library doesn't define __OBJC__ because it also changes its declarations if this is already defined. You can't simply define __OBJC__ at the beginning of a program however, as it will cause a failure to build with libobjc.a. The proper way to patch in compatibility is to modify the end of objc.h (located at: .../[version]/include/objc/objc.h), and import it in your program before you import the windows headers.
Patch to objc.h
157 IMP objc_msg_lookup(id receiver, SEL op); 158 158 #define __OBJC__ /* Insert Patch Here */ 159 #ifdef __cplusplus 160 } 161 #endif 162 163 #endif /* not __objc_INCLUDE_GNU */
Test Build
Here's a bare-bones project you can throw together to test if your C::B settings will compile ObjC correctly. You can't actually test with just strict C, since any problems with the Objective-C compiler will only manifest when using ObjC functionality.
main.m
#import <stdlib.h> #import "TestObject.h" int main(int argc, char** argv) { TestObject *aTestObject = [[TestObject alloc] init]; printf("Initial Value: %d\n", [aTestObject value]); printf("+45 Value: %d\n", [aTestObject add: 45]); printf("-63 Value: %d\n", [aTestObject subtract: 63]); [aTestObject add: 103]; printf("+103 Value: %d\n", [aTestObject value]); return (EXIT_SUCCESS); }
TestObject.h
#import <objc/Object.h> @interface TestObject : Object { int internalInt; } - (int)add:(int)anInt; - (int)subtract:(int)anInt; - (int)value; @end
TestObject.m
#import "TestObject.h" @implementation TestObject - (id)init { if ((self = [super init])) { internalInt = 0; } return self; } - (int)add:(int)anInt { internalInt += anInt; return internalInt; } - (int)subtract:(int)anInt { internalInt -= anInt; return internalInt; } - (int)value { return internalInt; } @end
Objective-C Library Licensing
Unlike other libraries included with GCC, the Objective-C library may be statically linked into a project without extending the GNU GPL to that project. Although the library is covered under the GNU GPL itself, it has a special exemption in its license because it is a necessary library to compile a language.
License Exemption
/* */ | https://wiki.codeblocks.org/index.php/Installing_Objective-C_Compiler | CC-MAIN-2022-05 | refinedweb | 1,159 | 55.54 |
> > Yep, but that didn't pass the davem test, right? > > > > Anyway, I expect to have more free time to spend on that kind of stuff > > now. Did 2.6.25 come earlier than anticipated, or what? Have these > > drivers been removed in your tree as well? > > 2.6.24 has been out for 2 weeks. The ESP drivers were removed from the > scsi-misc tree, and the plan seems to be removal from Linus's tree for > 2.6.25. Right - that still leaves a brief window to procrastinate. First the newly introduced falconide panic, though. Geert: this bit looks fishy - hw->io_ports[IDE_DATA_OFFSET] = ATA_HD_BASE; for (i = 1; i < 8; i++) hw->io_ports[i] = ATA_HD_BASE + 1 + i * 4; hw->io_ports[IDE_CONTROL_OFFSET] = ATA_HD_CONTROL; The last line should read hw->io_ports[IDE_CONTROL_OFFSET] = ATA_HD_BASE + ATA_HD_CONTROL; at the very least. OTOH I'm not sure falconide_setup_ports ever got called ... the 39 in a1 looks like it might be the control offset but the segfault was at 0. Anyway, with unpatched 2.6.24 (commit df922075f2a55b1ae71a6fe589c1cc1b91381f4f) and the above change I see no segfault. I see, however, a identify message like hda: aSgr e6mk8 and hda: 0 sectors which is somewhat fatal. Did the byte swapping in the IDE driver get removed? We had this in ide-iops.c as late as 2.6.19: #ifdef M68K_IDE_SWAPW if (M68K_IDE_SWAPW) { /* fix bus byteorder first */ u_char *p = (u_char *)id; u_char t; for (i = 0; i < 512; i += 2) { t = p[i]; p[i] = p[i+1]; p[i+1] = t; } } #endif That's still needed for Atari and Q40. Again, may be due to me using vanilla sources instead of Geert's quilt patches, though I saw no trace of that in the patch titles. Putting that bit back in gives me a bootable kernel (on ARAnyM). Yay for AranyM! BTW: the borked ATA_HD_CONTROL register bug will alsi hit macide (and perhaps others). gayle.c passes the sanitized control port value to gayle_setup_ports so it's in the clear. HTH, Michael | https://lists.debian.org/debian-68k/2008/02/msg00070.html | CC-MAIN-2015-32 | refinedweb | 334 | 83.66 |
Suppose you encounter a (single-player) riddle or a puzzle that you don't know how to solve. Let's also suppose that this puzzle involves moving between several states of the board with an enumerable number of moves emerging from one state. In this case, LM-Solve (or Games::LMSolve on CPAN) may be of help.
LM-Solve was originally written to tackle various types of the so-called logic mazes that can be found online. Nevertheless, it can be extended to support many other types of single-player puzzles.
In this article, I will demonstrate how to use LM-Solve to solve a type of puzzle that it does not know yet to solve.
Installation
Use the CPAN.pm module
install Games::LMSolve command to
install LM-Solve. For instance, invoke the following command
on the command line:
$ perl -MCPAN -e 'install Games::LMSolve'
That's it! (LM-Solve does not require any non-base modules, and should run on all recent versions of Perl.)
The Puzzle in Question
The puzzle in question is called "Jumping Cards" and is taken from the Macalester College Problem of the Week No. 949. In this puzzle, we start with eight cards in a row (labeled 1 to 8). We have to transform it into the 8 to 1 sequence, by swapping two cards at a time, as long as the following condition is met: at any time, two neighboring cards must be in one, two, or three spaces of each other.
Let's experience with this puzzle a bit. We start with the following formation:
1 2 3 4 5 6 7 8
Let's swap 1 and 3, and see what it gives us:
3 2 1 4 5 6 7 8
Now, we cannot exchange 1 and 4, because then, 1 would be close to the 5, and 5-1 is 4, which is more than 3. So let's exchange 2 and 1:
3 1 2 4 5 6 7 8
Now we can exchange 2 and 4:
3 1 4 2 5 6 7 8
And so on.
Let's Start ... Coding!
The
Games::LMSolve::Base class tries to solve a game by iterating
through its various positions, recording every one it passes through,
and trying to reach the solution. However, it does not know in advance
what the games rules are, and what the meaning of the positions
and moves are. In order for it to know that, we need to inherit it and
code several methods that are abstract in the base class.
We will code a derived class that will implement the logic specific to the Jumping Cards game. It will implement the following methods, which, together with the methods of the base class, enable the solver to solve the game:
input_board
pack_state
unpack_state
display_state
check_if_final_state
enumerate_moves
perform_move
render_move
Here's the beginning of the file where we put the script:
package Jumping::Cards; use strict; use Games::LMSolve::Base; use vars qw(@ISA); @ISA=qw(Games::LMSolve::Base);
As can be seen, we declared a new package,
Jumping::Cards,
imported the
Games::LMSolve::Base namespace, and inherited
from it. Now let's start declaring the methods. First, a method to
input the board in question.
Since our board is constant, we just return an array reference that contains the initial sequence.
sub input_board { my $self = shift; my $filename = shift; return [ 1 .. 8 ]; }
When
Games::LMSolve::Base iterates over the states, it stores data
about each state in a hash. This means we're going to have to provide a
way to convert each state from its expanded form into a uniquely
identifying string. The
pack_state method does this, and in
our case, it will look like this:
# A function that accepts the expanded state (as an array ref) # and returns an atom that represents it. sub pack_state { my $self = shift; my $state_vector = shift; return join(",", @$state_vector); }
It is a good idea to use functions like
pack,
join
or any other serialization mechanism here. In our case, we simply
used
join.
It is not very convenient to manipulate a packed state, and so we need
another function to expand it.
unpack_state does the
opposite of
pack_state and expands a packed state.
# A function that accepts an atom that represents a state # and returns an array ref that represents it. sub unpack_state { my $self = shift; my $state = shift; return [ split(/,/, $state) ]; }
display_state() converts a packed state to a user-readable string. This
is so that it can be displayed to the user. In our case, the comma-delimited
notation is already readable, so we leave it as that.
# Accept an atom that represents a state and output a # user-readable string that describes it. sub display_state { my $self = shift; my $state = shift; return $state; }
We need to determine when we have reached our goal and can terminate the
search with a success. The
check_if_final_state function
accepts an expanded state and checks if it qualifies as a final
state. In our case, it is final if it's the 8-to-1 sequence.
sub check_if_final_state { my $self = shift; my $coords = shift; return join(",", @$coords) eq "8,7,6,5,4,3,2,1"; }
Now we need a function that will tell the solver what subsequent
states are available from each state. This is done by enumerating a
set of moves that can be performed on the state. The
enumerate_moves function does exactly that.
# This function enumerates the moves accessible to the state. sub enumerate_moves { my $self = shift; my $state = shift; my (@moves); for my $i (0 .. 6) { for my $j (($i+1) .. 7) { my @new = @$state; @new[$i,$j]=@new[$j,$i]; my $is_ok = 1; for my $t (0 .. 6) { if (abs($new[$t]-$new[$t+1]) > 3) { $is_ok = 0; last; } } if ($is_ok) { push @moves, [$i,$j]; } } } return @moves; }
What
enumerate_moves does is iterate over the indices of the
locations twice, and checks every move for the validity of the
resultant board. If it's OK, it pushes the exchanged indices to the
array
@moves, which is returned at the end.
We also need a function that will translate an origin state and
a move to a resultant state. The
perform_move function
performs a move on a state and returns the new state. In our case,
it simply swaps the cards in the two indices specified by the move.
# This function accepts a state and a move. It tries to perform the # move on the state. If it is successful, it returns the new state. sub perform_move { my $self = shift; my $state = shift; my $m = shift; my @new = @$state; my ($i,$j) = @$m; @new[$i,$j]=@new[$j,$i]; return \@new; }
Finally, we need a function that will render a move into a user-readable string, so it can be displayed to the user.
sub render_move { my $self = shift; my $move = shift; if (defined($move)) { return join(" <=> ", @$move); } else { return ""; } }
Invoking the Solver
To make the solver invokable, create an instance of it in the
main namespace, and call its
main() function. This will
turn it into a script that will solve the board. The code is this:
package main; my $solver = Jumping::Cards->new(); $solver->main();
Now save everything to a file, jumping_cards.pl (or
download the complete one), and invoke
it like this:
perl jumping_cards.pl --norle --output-states.
The
--norle option means not to run-length encode the moves.
In our case, run-length encoding will do no good, because a move can
appear only once (or else its effect will be reversed).
--output-states causes the states to be displayed in the
solution.
The program thinks a little and then outputs:
solved solved 1,2,3,4,5,6,7,8: Move = 0 <=> 1 2,1,3,4,5,6,7,8: Move = 1 <=> 2 2,3,1,4,5,6,7,8: Move = 1 <=> 3 2,4,1,3,5,6,7,8: Move = 4 <=> 5 2,4,1,3,6,5,7,8: Move = 0 <=> 4 6,4,1,3,2,5,7,8: Move = 2 <=> 3 6,4,3,1,2,5,7,8: Move = 0 <=> 1 4,6,3,1,2,5,7,8: Move = 0 <=> 7 8,6,3,1,2,5,7,4: Move = 6 <=> 7 8,6,3,1,2,5,4,7: Move = 3 <=> 5 8,6,3,5,2,1,4,7: Move = 2 <=> 7 8,6,7,5,2,1,4,3: Move = 1 <=> 2 8,7,6,5,2,1,4,3: Move = 4 <=> 6 8,7,6,5,4,1,2,3: Move = 5 <=> 7 8,7,6,5,4,3,2,1
Which is a correct solution to the problem. If you want to see
a run-time display of the solving process, add the
--rtd
switch.
Conclusion
LM-Solve is a usable and flexible framework for writing your own solvers for various kind of puzzles such as the above. Puzzles that are good candidates for implementing solvers have a relatively limited number of states and a small number of states emerging from each origin state.
I found several solitaire games, such as Freecell, to be solvable
by methods similar to the above. On the other hand, Klondike
and other games with
talon, are very hard to solve using
such methods, because the
talon expands the number of states
a great deal.
Still, for most "simple-minded" puzzles, LM-Solve is very attractive as a solver framework. Have fun! | http://www.perl.com/pub/2003/11/17/lmsolve.html | crawl-003 | refinedweb | 1,580 | 68.5 |
View Poll Results: If you read it, did you find DirectJNgine User's Guide adequate?
- Voters
- 54. You may not vote on this poll
Yes
No
I
- Pedro Agulló, Barcelona (Spain)
Agile team building, consulting, training & development
DirectJNgine: - Log4js-ext:
Thank you for the quick answer, I found the solution:
Code:
MyProvider.direct.REMOTING_API.maxRetries = 0; //setting the maximum no. of retries MyProvider.direct.REMOTING_API.timeout = 100000; //setting the timeout value Ext.Direct.addProvider(MyProvider.direct.REMOTING_API);
thanks,
Lee
deploy directjngine on linux is not working
deploy directjngine on linux is not working
Hi,
When I deploy directjngine on linux (on Jboss AS) there is a problem in the deployment.
I see that the generated files are created lower case:
Api.js instead of API.js (API.js exists but it is empty, probably copied from the source dir).
when I change the name to API.js it is working.
In windows env there were no problems with this.
Any ideas? can I put the generated file from windows as a source in my linux env as a solution?
thanks,
Lee
Never heard of such problem before, and there is a lot of people out there using DJN in Linux -I myself included.
Are you completely sure you are using the *exact* api file name you specified in web.xml?
As a workaround, you might specify in web.xml the exact name the generated file has, and call it a day.Pedro Agulló, Barcelona (Spain)
Agile team building, consulting, training & development
DirectJNgine: - Log4js-ext:
Facing problem while implementing DirectJNgine
Facing problem while implementing DirectJNgine
I am facing a lot of problems while implementing DirectJNgine in Extjs 4 MVC structure. Could any one please give me DirectJNgine example using Extjs4 MVC structure.
Need to upgrade directjngine for Ext JS 4.x?
Need to upgrade directjngine for Ext JS 4.x?
We have an application which uses the DirectJNgine version 1.0. Our currently application is written using Ext JS 3.2. I'm trying to see if I can convert/rewrite our application to work with Ext JS 4.2 and rewriting the server at the same time would be quite a bit of work. Do we need to upgrade DirectJNgine to the latest release to work with Ext JS 4.2? If we had to upgrade, what impact would there be on our existing Ext JS 3.2 application?
Thanks.
Jim
Of course, your mileage may vary.Pedro Agulló, Barcelona (Spain)
Agile team building, consulting, training & development
DirectJNgine: - Log4js-ext:
Call inter DirectAction
Call inter DirectAction
Hi
Firstly thank you for this awesome piece of software!
Now, is there a way to call a method of a DirectAction class from another DirectAction class?
Code:
@DirectAction( action="Action1") public class ActionClass1{ @DirectMethod public Object getStuff() { .... return foo; } } @DirectAction( action="Action2") public class ActionClass2{ @DirectMethod public Object getOtherStuff() { .... ActionClass1 c1 = this.getDirectAction("Action1"); return c1.getStuff(); } }
DirectJNgine with Ext JS 4.2
DirectJNgine with Ext JS 4.2
It all looks good but before I start looking too deeply into DirectJNgine I would like to know a little about the status of the project. First question that come to mind is
- Will DirectJNgine work with Ext JS 4.2 ? (only Ext JS 4.1 is mentioned in the docs)
- Is the project being actively maintained ? I'm fully aware that no recent releases sometimes simply means that the code is stable and feature complete and therefore no reason to release new stuff. I hope that is the case for DirectJNgine.
Thank you.) | http://www.sencha.com/forum/showthread.php?73027-Ext-Direct-Java-based-implementation/page46&p=993266 | CC-MAIN-2014-42 | refinedweb | 590 | 58.28 |
because they are individually very small. I just looked and the vastmajority of the alloc_percpu users are counters.I just did a rough count in include/linux/snmp.h and I cameup with 171*2 counters. At 8 bytes per counter that is roughly2.7K. Or about two thirds of a 4K page.What makes this is a challenge is that those counters are per networknamespace, and there are no static limits on the number of networknamespaces.If we push the system and allocate 1024 network namespaces we wind upneeding 2.7MB per cpu, just for the SNMP counters. Which nicely illustrates the principle that typically each individualper cpu allocation is small, but with dynamic allocation we have thechallenge that number of allocations becomes unbounded and in some casescould be large, while the typical per cpu size is likely to be very small.I wonder if for the specific case of counters it might make sense tosimply optimize the per cpu allocator for machine word size allocationsand allocate each counter individually freeing us from the burden ofworrying about fragmentation.The pain with the current alloc_percpu implementation when workingwith counters is that it has to allocate an array with one entryfor each cpu to point at the per cpu data. Which isn't especially efficient.Eric | http://lkml.org/lkml/2009/1/21/130 | CC-MAIN-2013-20 | refinedweb | 215 | 55.74 |
SDL_SetVideoModeSection: SDL API Reference (3)
Updated: Tue 11 Sep 2001, 23:01
Index Return to Main Contents
NAMESDL_SetVideoMode- Set up a video mode with the specified width, height and bits-per-pixel.
SYNOPSIS
#include "SDL.h"
SDL_Surface *SDL_SetVideoMode(int width, int height, int bpp, Uint32 flags);
DESCRIPTION
Set up a video mode with the specified width, height and bits-per-pixel.
If bpp is 0, it is treated as the current display bits per pixel.
The flags parameter is the same as the flags field of the SDL_Surface structure. OR'd combinations of the following values are valid.
- the colors you request with SDL_SetColors or SDL_SetPalette.
- SDL_DOUBLEBUF
- Enable hardware double buffering; only valid with SDL_HWSURFACE. Calling SDL_Flip will flip the buffers and update the screen. All drawing will take place on the surface that is not displayed at the moment. If double buffering could not be enabled then SDL_Flip will just perform a SDL_UpdateRect on the entire screen.
- generated and SDL_SetVideoMode can be called again with the new size.
- SDL_NOFRAME
- If possible, SDL_NOFRAME causes SDL to create a window with no title bar or frame decoration. Fullscreen modes automatically have this flag set.
- Note:
Whatever flags SDL_SetVideoMode could satisfy are set in the flags member of the returned surface.
- Note:
Index
Random Man Pages:
SSL_alert_type_string_long
ExtUtils::Miniperl
s3virge
pbmtoepson | http://www.thelinuxblog.com/linux-man-pages/3/SDL_SetVideoMode | CC-MAIN-2017-22 | refinedweb | 219 | 66.64 |
As I write this article, Texas and Oklahoma are thawing out from a long ice storm. Drivers, fearing not just the ice but other brash Texans driving on it, are beginning to emerge again. My life is approaching some semblance of normalcy after three days of hibernation. I experienced a brief freeze of a different kind after switching from the Java language to Ruby. When I worked with Java projects, I could always find that special Spring library or Eclipse component to solve some niche problem. When Ruby on Rails was new, I'd often need to write it myself. Happily, that freeze too is beginning to thaw nicely, thanks to an effective plug-in architecture that thousands of people have used to extend Rails.
If you've spent any time at all with Rails, you've doubtless noticed the
acts_as commands in ActiveRecord. Though ActiveRecord deals with persistence, you often want to add behavior to your classes beyond database storage and retrieval. For example, by using
acts_as_tree, you can add tree-like behavior to a class with a
parent_id attribute. By saying nothing more than
acts_as_tree in your ActiveRecord model, you can dynamically add methods to manage the tree, such as methods that retrieve the parent record or child record. Over the past month, I've been able to find Rails plug-ins to handle voting, versioning, Ajax, composite keys, and all manner of features that basic Rails doesn't support.
Extension models in Rails, which build on top of features in the Ruby language, look dramatically different from those in the Java language. In this article, I crack open
acts_as plug-ins so you can see the extension model from the inside. I provide a partial production example rather than build a toy end-to-end scenario to cover more ground and give you the flavor of real plug-ins and how they're used in real production code.
As many of you know, a state machine is a mathematical expression of a system's state. A state machine has a mixture of nodes representing states and transitions between them. At any given time, a state machine has one active state, also called a current state. Events trigger transitions between states. To illustrate the concept, I'll show an example from my current day job: development and maintenance of ChangingThePresent.org (CTP), a marketplace for nonprofits and donors (see Resources). CTP lets nonprofits submit information about their organizations and a series of gifts -- such as one hour of a cancer researcher's time or books for one student -- letting donors use a simple shopping cart to make a charitable contribution as a gift in another's name. Collecting all of that information leads to logistical problems, so I chose to simplify the workflow with a state machine.
To solve this problem, I use a third-party plug-in, written by Scott Barron, called
acts_as_state_machine (see Resources). Like many Rails plug-ins,
acts_as_state_machine uses a combination of Ruby capabilities and exclusive Rails features to provide not just a library, but also a domain-specific language (DSL), providing a nice experience for users.
A customer submits content to CTP (
submitted state). A CTP administrator then receives the content possibly to edit (
processing state). If CTP makes edits, the nonprofit should be able to approve those changes (
nonprofit_reviewing state). When CTP or the nonprofit approves the content, CTP can show the content on the site (
accepted state). Figure 1 is a pictorial representation of the state machine:
Figure 1. State machine for CTP
Using the plug-in, I can decorate my class object directly, using a DSL to represent the various states, transitions between them, and the events that fire those transitions. Listing 1 shows a simplified version of the state machine that I use to manage nonprofits at CTP:
Listing 1: Example state machine
You might not have seen all of these Ruby features before, but the language describing the state machine flows nicely. You see descriptions of each of the states, followed by the events supported by the state machine. After each event, you see a series of transitions that each event will fire.
Each statement represents valid Ruby syntax. After the class definition, you see
acts_as_state_machine :initial => :created, :column => 'status'. As a Java developer, you may find it strange to find a method invocation instead of a method definition. Ruby refers to these method invocations at the class level as macros. Ruby often uses macros to add capabilities to each class as it's loaded. In fact, method definitions --
def -- are no more than Ruby macros.
Next, you see a series of states, such as
state :submitted. These are method invocations, each taking a symbol as a single parameter. (A symbol is a user-defined name.) The
event command is also a method invocation, taking a symbol (which defines the event's name) and a closure, which defines the transitions.
Each transition is a method invocation followed by a hash table. In Ruby, you represent a hash map as
key => value pairs, separated by commas, and {enclosed in braces}. When you use a hash map as a function call's last parameter, the braces are optional. You can see that the methods -- state, transition, and event -- combined with closures and hash maps, make a nice DSL.
To use the state machine, I can instantiate a
Nonprofit object and call methods on it for each event, followed by a
!, as in Listing 2:
Listing 2. Manipulating the state machine
The
! is a Rails convention for methods that modify and save an attribute in one step. So the requirements for the state machine plug-in are clear. I need:
- A convenient place to put the state machine code.
- A way to specify my class methods, which are required for the DSL.
- A way to attach my instance methods to
Nonprofitor any other target class.
The rest of this article walks you through the plug-in. If you want to pull down the code and follow along, download the
acts_as_state_machine plug-in. (See Resources for a link to Scott Barron's site and follow his directions for getting the plug-in through Subversion.) Navigate to trunk/lib. You'll find the acts_as_state_machine.rb file. Find the initialization code in trunk/init.rb. These are the only two files you need.
In principle, all
acts_as plug-ins work the same way. You always follow these steps to build an
acts_as module:
- Create a module. Begin the name of a class method (your initialization macro) with
acts_as_.
- In some initialization code, open the
ActiveRecordbase class and add your
acts_as_module.
- Extend the behavior of the target class in an
acts_as_function (for example,
acts_as_state_machine).
Take a quick look at the initialization code in init.rb, shown in Listing 3:
Listing 3. Initialization code for acts_as_state_machine
This code opens the core
ActiveRecord class (
ActiveRecord::Base) and adds
acts_as_state_machine. The
class_eval method opens the class and runs the following closure in the context of the class. Whew. That's a mouthful. In practice, the concept is simple: the code opens up the
ActiveRecord base class and mixes in the
ScottBarron::Acts::StateMachine module. In Ruby, you can open up any class and redefine it quickly.
This capability is one of Ruby's greatest strengths because of the increased flexibility. But the capability is a weakness too. Too much flexibility can lead to code that's difficult to understand and maintain, so be careful. Now, open the acts_as_state_machine.rb file to see what code gets mixed in.
At this point, I'm going to steer away from the details of implementing the state machine. Instead, I concentrate on exposing the interface to the state machine through the plug-in. Listing 4 shows the module definition and some of the interface of the state machine itself:
Listing 4. The module structure
At the top of Listing 4, you see a nested module definition. A module has method definitions, but no base inheritance hierarchy. Instead, you can attach modules to any existing Ruby class. If the concept is new to you, think of a module as an interface plus the implementation for that interface. The nice thing about a module is that you can attach its functionality to any existing Ruby class, and you can attach as many as you want. You can also leverage a class's existing capabilities. This technique is called mixing in. C++ uses multiple inheritance to provide a similar capability, but with ugly complications. The Java founders eliminated multiple inheritance to address those complications. With modules, you can get some of the benefits of multiple inheritance without the sticky complications. Languages such as Smalltalk and Python also support mix-in inheritance.
The rest of Listing 4 shows some of the mundane details that go into implementing the state machine. You just need to know that these classes provide a stand-alone implementation of a state machine. The rest of the code is far more interesting because it deals with exposing that state machine interface to the plug-in's clients.
Recall that a plug-in author needs three things: a place to put the implementation, a way to expose the DSL (the class methods), and a way to expose the instance methods for the state machine. These include the event methods that you saw in action in Listing 3. Listing 4 provided the place to put the implementation. The next slice of code handles the DSL.
The
acts_as plug-in architecture has one anchor point: the
acts_as macro. Clients of the
acts_as plug-in introduce this method with a method invocation in the target class. In my case, I invoke the
acts_as in Listing 1 from the
Nonprofit class with this line of code:
Now take a look a Listing 5, which provides the
ActMacro for
acts_as_state_machine. This class handles the attributes for the module and introduces the various class and instance methods.
Listing 5. Adding acts_as
The module in Listing 5 has a single method:
acts_as_state_machine. The method does five tasks:
- Introduces class methods
- Handles state machine exceptions
- Manages attributes
- Introduces instance methods
- Handles before and after filters
The
acts_as_state_machine method first introduces class methods. (You can see a precise listing of these methods in Listing 6.) Next, the method handles exceptions. In this case, the only exception occurs when the client doesn't specify an initial state. Skip the inheritable attributes briefly -- I dive into those next.
The self.send method introduces instance methods. (Listing 7 shows those in detail.) Finally, the
before and
after filters are ActiveRecord macros that call the
set_initial_state and
run_initial_state_actions before and after ActiveRecord creates a record.
Go back to the
write_inheritable_attribute and
class_inheritable_reader macros. You may be wondering why the module doesn't use simple inheritance. The reason is simple: The module has an inheritance hierarchy of its own. These macros allow the module to project these attributes onto the target class --
Nonprofit in this example. The most important attributes are
state_column and a series of transition tables containing the states, events, and transitions. Now it's time to add the class methods that form the DSL.
Adding class and instance methods
In Listing 6, you can finally see the magic introducing the DSL:
Listing 6. Class methods for acts_as_state_machine
The
event and
state macros, as promised, are simple methods, defined in a module called
ClassMethods. The
event method reads the transition table attribute, followed by the event table attribute. The method adds the event to the event table and then dynamically defines a method for the event, wiring the new method to the
fire method on
event.
After the
event method, the module defines the
state method. This method reads the state table and adds the new state. Then, it adds a convenience method to the target class, returning
true if the instance is in the current state. For example,
nonprofit.submitted? would return
true if the status flag were
submitted. Now, the DSL is completely supported.
Instance methods work exactly like class methods. Listing 7 shows the instance method:
Listing 7. Instance methods for acts_as_state_machine
ActMacro opens the class and adds them. There's no need to go through the
read_inheritable_attribute macro to use attributes because these are class instance variables defined by ActiveRecord. I show only the methods that set the initial state and return the current state. The rest work in the same way.
The first method in Listing 7 sets the initial state, updating an existing ActiveRecord column. Recall that I set the column's name when I invoked
ActMacro. The
current_state method simply returns the instance variable's value. The
send method invokes the method named by a single symbol parameter, which in this case is the name of the
state_column.
You might think it would be simpler just to build a state machine and use it as a library. The
acts_as plugin is much nicer. It lets you effectively add a state-machine column to your database. Other plug-ins let you do versioning, build in audit histories, handle images, and perform hundreds of other simple tasks, just as if those tasks were a seamless integration between the Rails environment and the database.
You may have used the Java language to integrate Eclipse plug-ins, Ant tasks, or Spring libraries into your code base or to introduce EJB components. Many ideas from the Java community changed the way that developers think about extension. This whirlwind tour of Rails
acts_as plug-ins shows a new way to think about it. The flexibility of the Ruby language has changed my thinking about extensions. The
acts_as plug-ins allow a new generation of developers to try their hand at writing extensions. The result is a new wave of extensions for Rails. Many of these techniques are available to Java developers too, through aspect-oriented programming or bytecode enhancement.
Next time, I'll wrap up the series with an in-depth comparison between solving a difficult problem using Ruby and my experiences on the Java platform. Until then, keep crossing borders.
Learn
- Java To Ruby: Things Every Manager Should Know (Pragmatic Bookshelf, 2006): The author's book about when and where it makes sense to make a switch from Java programming to Ruby on Rails, and how to make it.
- Beyond Java (O'Reilly, 2005): The author's book about the Java language's rise and plateau and the technologies that could challenge the Java platform in some niches.
- Plugins in Ruby on Rails: Check out the documentation for the Rails plug-in architecture.
- acts_as_state_machine: The Rails plug-in that allows an ActiveRecord model to function as a state machine.
- Changing The Present: The nonprofit marketplace, built in Ruby on Rails, that provided the example for this article.
- "Class and instance variables in Ruby" (John Nunemaker, RailsTips.org, November 2006): Dealing with class and instance variables, when you're possibly dealing with multiple inheritance, can be tricky. This article walks you through an example of a technique called inheritable attributes.
- The Java technology zone: Hundreds of articles about every aspect of Java programming.
Discuss
- Check out developerWorks blogs and and Rails: Up and Running. He spent 13 years at IBM and later formed the RapidRed consultancy, where he specialized in lightweight development strategies and architectures based on Ruby, and in the Ruby on Rails framework. He is now the CTO of WellGood LLC, a company that is forming a marketplace for nonprofit organizations and charitable giving. | http://www.ibm.com/developerworks/web/library/j-cb03137/index.html | crawl-002 | refinedweb | 2,582 | 64.51 |
Joerg Schilling schrieb am 2006-01-30:> Matthias Andree <matthias.andree@gmx.de> wrote:> > > Joerg Schilling schrieb am 2006-01-30:> >> > > Let me ask again:> > > > > > Is there a way to get (or construct) a closed view on the namespace > > > for all SCSI devices?> >> > Of course there is, /dev/sg*.> >> > But that is not what you're _actually_ asking - you appear to desire a> > unified namespace for SCSI + ATAPI + whatever, and the answer to that> > was /dev/*.> > I am only asking for a unique name space for all devices that talk SCSI.That is not the same.> And please: read the SCSI Standard on t10.org to learn that ATA is just one> of many possible SCSI transports.The t10.org front page mentions ATAPI links, and the links section leadsto t13.org for ATAPI. And now?Besides that, Linux is not currently implemented to make everybody andtheir dog look like SPI with ID, LUN and everything, and until now youhave not presented anything but phantoms (such as ATAPI tapes) tosupport your point why it should do that. No wonder people are losinginterest in the discussion if you don't even answer questions what thecurrent Linux interface don't give you, and you haven't seriouslyresponded to my suggestion to simply scan all transports in libscg, forinstance, "" (sg+pg), ATA:, ATAPI, RSCSI:.-- Matthias Andree-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | http://lkml.org/lkml/2006/1/30/226 | CC-MAIN-2014-42 | refinedweb | 251 | 63.49 |
various reasons, CS 1110 exams are given on paper and involve writing code by hand. The goal of this lab is to prepare you for that: both the on-paper coding and the idea of being tested.
We use a system called TPEGS to scan, grade, and return your paper exams. For this to work, you need to fill in a bubble sheet on the first page of your exam. The bubble region looks like this:
You fill in your computing ID, skipping rows if you have less than 6 characters in your id, like this:
The footers are read optically, so please fill in the bubbles darkly (either with ink or dark pencil).
This lab will run as follows:
The problems we prepared for the TAs to review are here
The versions the TAs had, with solutions and rubrics, are here
Every piece of code looks a little different and we don’t expect perfection on paper, but here are some thing we do look for:
Neatness. It should be easy to read what you wrote.
def baz(x, y):not
define baz[x, y])
Correctness. The algorithm you write should solve the problem given.
Constraints. Follow the directions…
Write a function named, don’t name yours
xyxxy
quuxinstead
Write a functiongive us a function, not a program
We’ll show you an actual point break-down after you code—we make custom rubrics for each question, often giving away part of the answer, so you won’t get to see the rubric before you code.
In addition to coding-on-paper, we typically include
We might ask you what example code does, such as
What does the following print?
def f(g): global h g = g + g h = g print(g) print(h) g = "3" h = 4 f(g) print(g) print(h)
We might ask you for the type, value, or both of an expression; for example, we might expect you to identify that
2 * 3 / 2 is value
3.0, type
float.
We might ask open-ended questions, like
What is one advantage of writing functions in your code?
We don’t ask very many of these kinds of questions because it is hard to find questions where all instructors agree on the right grading policy, but we like to ask at least a few.
We might ask questions about Python syntax and semantics, such as
Which of the following is an error?
2 * 3
'2' * 3
2 * '3'
'2' * '3'
We try to design the exam so that the median student completes it before the 50 minutes are up. Hitting this goal is not easy, but we try…
Spring 2017 Exam 1 is available, as is its key and gradign rubric. Some minor edits were made to the rubric during grading, which are not reflected here.
input– and related terminology like
prompt
int– what it does given a string or a float and when it creates an error
str– what it does given an integer or a float
float– what it does given a string or an integer
len– to find length of strings
type– to find the type of a value
-,
+,
*,
/,
%,
//,
**
type(4/2)is
<class 'float'>not
<class 'int'>; that
+works on strings but
-does not; that
*can work with a string and an integer but not with two strings; etc).
+=)
andand
or
<,
<=,
==,
!=,
>=, and
>
=
globalkeyword
1111
11.11
Trueand
False
'single',
"double",
'''triple-single''',
"""triple-double""", and
'with \'escape sequences\' for internal quotes'
def name(argument, list):
return: what it does, including that it ends the function
name(argument, values)
if,
elif, and
else | http://cs1110.cs.virginia.edu/lab05-paper.html | CC-MAIN-2017-43 | refinedweb | 601 | 70.47 |
Created on 2012-05-03 21:04 by eric.smith, last changed 2020-01-29 07:23 by eric.smith. This issue is now closed.
DirsOnSysPath doesn't clear sys.path_importer_cache, so it seems you'd always want to use import_state, which does clear it.
We might also want to modify import_state to remember the original objects, not just their values. DirsOnSysPath does do this, for sys.path.
If we do this, we should probably move import_state to test.support.
Also, couldn't import_state do with sys.modules what DirsOnSysPath does with sys.path? It could restore both the object and its contents.
Yes, it could do all of this. One possibility that I was thinking of, was this could be a setUp()/tearDown() thing as well instead of a context manager. Another option is a simple decorator. Either way it might be easier to have it just save state and then in the body of the code set everything as desired instead of in the context manager's init.
I tend to like context managers, or helpers that work with addCleanup, so that I keep the scaffolding next to the test code. setUp and tearDown are better in some cases, though. It is also possible to have an helper work as a decorator and a context manager and a setUp-tearDown thing with small effort.
Clean up code in test_pkgutil once this issue is fixed. See issue 14817.
Here's what I imagine the new function will look like. I propose moving it to test.support and using it outside of importlib, specifically for the PEP 420 tests.
Also for use in test_pkgutil.
So from what I can tell you are advocating not resetting anything by default but instead only save the details and then reset it later. That's fine with me (aligns more with the warnings context manager), the importlib tests will simply need to be updated so as to fix their assumptions that everything gets cleared.
Actually, I was planning on resetting everything, but I haven't gotten that to work yet. I can't figure out why (but I will!).
With the current patch, where things are not reset, the only test I had to change was test_path_importer_cache_empty_string. That change is in the attached -0 diff.
I can't decide which way I prefer it. I might add a parameter to control the behavior.
The current tests don't like setting sys.modules to [].
I like resetting everything (including sys.modules) back to the original state. Otherwise some tests, which do things like "import foo", affect later tests.
So, I think I'll leave the patch as-is. I'll rename it, fix all references to it, then check it in. After that I'll start using it in other tests.
sys.modules is tricky thanks to built-in modules not liking to be re-imported (and why import_state in importlib.test didn't reset it).
If only one test fails because of my assumption, then I guess blanking them out really isn't as important as I thought. And if you have to blank everything out for a test, then you are just careful to blank everything out, no matter how verbose it gets.
I understand about sys.modules. Maybe I'll create another context manager (say, sys_modules_state) that does the same for sys.modules. I can always stack them together.
When loading pure-Python namespace packages, I want to make sure they get removed before the next test.
I see three options (which can be combined). One is to keep using something like the uncache context manager to make sure the expected modules get removed. Two is to check the keys of sys.modules at the end of a context manager and if there are new keys either blindly clean up or raise an error/warning that stuff was left behind. Lastly is to leave all built-in modules (and maybe extension modules if you are worried they will do something silly during init) in sys.modules and then clear out the rest (although that might screw up importlib if we end up hiding importlib._bootstrap behind _frozen_importlib, in which case you will want to leave frozen modules as well or special-case _frozen_importlib).
Do we still care about this, Eric?
I don't think so. I don't think the patch even did what I wanted it to do. I'll close it. | https://bugs.python.org/issue14715 | CC-MAIN-2020-50 | refinedweb | 741 | 76.32 |
C Programming Style Guide
1 GeneralThis style guide is mandatory for all submitted work for grading (homework, projects, labs, exams). The purpose of the guide is not to restrict your programming but rather to establish a consistent style format for your programs. This will help you debug and maintain your programs, and help others (including your instructor) to understand them. As your programs grow in length and complexity, it is critical to use a consistent style. In the long run this will help you since one focus of this course is to build a foundation for later courses. Points will be deducted from submitted work that does not conform to this style guide.
2 Visual Layout"Whitespace" refers to newlines, space characters and tabs. In source code we do not generally use tabs — in fact, your editor should be replacing tab characters with an appropriate number of space characters. In many circumstances whitespace is not required in order for compilers to correctly compile source code, even though the result is unreadable to us. For example, the following is a perfectly valid program:
... but pretty hard to read. there are three major ways we use whitespace to format code for maximum clarity:
- whitespace separating elements of code: consistent use of whitespace transcends blank lines and indentation, it also looks at how spaces are used to separate elements of a line of code. the style guide recommends whitespace between operators and operands, except where precedence is highlighted by leaving out spaces.
- blank lines: in source code, use blank lines to separate chunks of code that accomplish distinct tasks. while to some extent this is taste and art, you should expect distinct functions to be separated by blank lines, and a long function body should usually be broken into chunks by blank lines as well.
- indentation: indentation highlights the block structure of programs, much as it does in formatting outlines. each level of block nesting must be indented by a consistent number of spaces (two in the emacs settings we provide you). new levels of indenting are introduced by function bodies, for, while and do-while bodies, the then and else blocks of an if statement, and struct definitions.
3 Curly braces, i.e. { }'sCurly braces, i.e.
{ }'s in C are used to create a "block" from one or more statements. the delineate the bodies of functions, loops and switch statements, struct definitions, and the then and else blocks of if statments. generally, one should either always put the opening curly brace at the end of the line, or on a new line by itself. (The exception is that a comment may follow an opening curly brace.)
Once again consistency is key. If the opening brace goes on a new line, the preference for this course is to keep the previous line's indentation — i.e. do not indent the curly brace. The closing curly brace is usually the only thing on its line, and should always be indented at the same level as the opening of the block.
4 CommentsComments should be indented consistently with the block of code they describe. Every file you write should start with a comment saying what the program/file is for and stating your name.
Comments can be divided into two general categories, strategic and tactical:
- Strategic comments are used to give the reader a general overview of what is going on. These comments appear at the beginning of files, before important functions, and above important blocks of code. Strategic comments tend to be written in sentences with an emphasis on explaining the big picture of what the block of code is designed to do.
- Tactical comments are designed to explain tricky areas of code, what parameters do, and hints about the control flow of the program. These comments should be intermixed in the code when needed. They should be shorter than strategic comments, in bullet format, and may be in inline format. One should, for instance, place a tactical comment next to the statement that assigns a fixed, non-obvious value to a variable.
/* Fahrenheit to Celsius Conversion * Dr. Roche, January 2017 */ #include "si204.h" int main() { // Read temperature in Fahrenheit double Tf; fputs("Enter temperature in Fahrenheit: ", stdout); Tf = readnum(stdin); // Compute temperature in Celsius double Tc; Tc = (Tf - 32)*(5/9.0); // .0 forces division as double // Write temperature in Celsius fputs("That is ", stdout); writenum(Tc, stdout); fputs(" degrees Celsius.\n", stdout); return 0; }
5 NamingVariables should have meaningful names. For example, consider a program that uses a variable to track the yards per carry of a football game. Such a variable should be called
yardsPerCarryvice
ypcfor program readability. This must be balanced against using names which are too long, which can obscure the code. (Fifteen or so characters approaches the “too long” limit.) It should be mentioned that this is most important for variables that have large scope — i.e. they are visible and need to be used either from different files or from widely separated lines in the same file. The code example above seems to violate this rule, but variables
Tfand
Tconly a appear, and are only in scope, within less than a dozen lines of code, and in the context of those few lines they are descriptive enough. Also, because this is an example embedded in a document, compactness of the code is very important.
Single letter variables or constants should generally not be used. An exception to this rule is when it is common practice to identify something with a single letter. An example of this is the coordinate system (x, y, and z). A second exception occurs in the use of loop counter variables where it is common practice to use variables like i and j as counters in for loops.
Function names and variable names should begin with a lower case letter. An identifier consisting of multiple names SHALL have each name distinguished by making the first letter of each name part (after the first) upper case (e.g. yardsPerCarry) or by using underscores (yards_per_carry).
Constants should be named in all upper case
letters. Example:
const int THISYEAR = 2017;
It's generally good to avoid lower case letter ‘L’, or the letter
‘O’ in names unless they are part of normal words. This is to avoid
confusion with the numbers 1 and 0. For example, is "
cell" c- e -
1- ONE or c- e- 1-1?
Avoid names that differ only in case, look similar, or differ only slightly. For example, InputData, InData and DataInput will certainly be confusing if used in the same program.
Names of functions should reflect what they do (printArray), or what they return (getAge). Boolean (true/false) variable names should sound like Yes/No things — "isEmpty" and "isFinished" are possible examples.
6 Miscellaneous but Important StuffNo line of code should go past 80 characters (sticking below 72 is even better). If a line of code becomes too long, break it up into pieces. Remember the compiler largely ignores extra whitespace in your programs that aren't in strings.
For breaking up strings, the compiler will automatically combine string literals that are on separate lines. For example, the following line of code:
could be written instead ascould be written instead as
fputs("This is my very long string.\nIt is so long that it will go past 80 characters and sadness will ensue.\n", stdout);
fputs("This is my very long string.\n" "It is so long that it will go past " "80 characters and sadness will ensue.\n", stdout);
Always use the most appropriate operator or construct for the work you want it to do. Good design and clarity take precedence over optimization. Try not to declare or use more variables than are necessary.
Numerical constants ("magic numbers") should not be coded directly. The only allowable exceptions are for 0, 1 or -1, and those which are not likely to change; for example code determining if a number is even can use the number 2 since it is not likely to change. Numerical constants must have a comment explaining the value if it is not evident from the name. | https://www.usna.edu/Users/cs/roche/courses/s17si204/admin/style.php | CC-MAIN-2018-43 | refinedweb | 1,360 | 62.88 |
See also: proposed Agenda, IRC log
VQ: agenda comments?
later, errata maintenance and issues list maintenance were added to the agenda
<DanC_> 23 Aug minutes
VQ: I made a small change re attendance 23 Aug
RESOLUTION: to approve 23 Aug minutes
<DanC_> minutes 12 July
RESOLUTION: to approve 12 July minutes.
VQ: upcoming telcons... grid...
NDW: I'm willing to scribe next week.
VQ: if I can't find Roy, then yes, please.
<timbl_> Regrests for 6th Sept and 13th
<timbl_> Also, Regrets for 4th October
<timbl_> Also, regrets for 8 and (29 is AC meeting) November
<ht> HST regrets for 13 September
HT: still working on getting somebody from [missed] to our ftf
VQ: agenda page is in
progress
... meeting goals? our June meeting focussed on long-term plans...
... perhaps try to close some issues this time?
DanC: re authentication, I'm
prepared to discuss, but not sure I'll get my writing
assignment done
... e.g. openid
HT: sounds plausible
... I have an XML 2005 paper in progress that's relevant to a number of issues/actions on languages/namespaces/etc.
<Zakim> DanC, you wanted to ... re URI scheme and certain vendors
VQ: see also next item for today
DanC: maybe namespaceDocument-8...
Ed: let's review priorities from
Jun ftf...
... e.g. grid
<DanC_> minutes June ftf in Cambridge
DanC: seems like we had several lists; do you remember which one?
VQ: I think so
Please send any comments to the iesg@ietf.org or ietf@ietf.org mailing lists ... From: ietf-announce-bounces@ietf.org On Behalf Of The IESG
Sent: Tuesday, July 12, 2005 3:33 PM
To: IETF-Announce
Subject: Last Call: 'Guidelines and Registration Procedures for new URI...
<timbl_> Draft of Formal TAG Last Call Comment on RFC2717bis/RFC2718bis
RESOLUTION: to send Comment on RFC2717bis/RFC2718bis as above in the name of the TAG to the IESG and the authors, with copy to uri@w3.org and www-tag@w3.org with follow-up directed to uri@w3.org
<scribe> ACTION: HT to send TAG comments on URI guidelines and registration procedures to the IETF [recorded in]
DanC: I'd like to be more explicit, a la "The dav: scheme is a poor use of this valuable shared resource, and should not be used as a precedent."
<scribe> ACTION: DanC to send individual comment on dav: to ietf [recorded in]
<DanC_> Revisiting namespaceDocument-8 Norman Walsh (Friday, 24 June)
NDW: yes, there was some
discussion...
... (a) JB objects to GRDDL alone on the basis that it doesn't ensure human-readability
... (b) [missed]
<Zakim> DanC, you wanted to ask for a particular namespace to focus on... xquery? xml schema? hypothetical-ml?
<ht>
<Norm> adaptation of XML Schema namespace document using GRDDL and RDDL 1.0
<Norm> adaptation of XML Schema namespace document using GRDDL and "RDDL 2"
DanC: yes, let's focus on
HT: so which...?
NDW: backing up... we've
considered alternatives to RDDL 1.0, but since then RDDL 1.0
deployment is becoming more and more substantial; e.g.
microsoft...
... and we have GRDDL that can work either way...
... yes, 2005/06/23-rddl/rddl1.xml is written in the dialect with large deployment
DanC: so is that "valid"?
HT: well, it's valid modular XHTML, but that's not supported by validat.w3.org
DanC: so text/xml by design?
NDW: well, I meant meant application/xhtml+xml
(try .htaccess, maybe)
$ HEAD '' Content-Type: text/xml; qs=0.9
DanC: so which media types are preferred? acceptable? for RDDL, application/xhtml+xml ? is application/xml ok?
HT: I think the answer is the
same as for XHTML. so no, not application/xml
... applicatin/xml is acceptable in some circumstances, e.g. when the client asks for it
DanC: so what exactly are the URIs in the RDDL vocabulary?
<Norm>
<Norm>
<ns0:purpose xmlns:ns0=""
<Norm>
<DanC_> I get 404 @
DanC: 4xx conflicts with "should make respresentation available". 2xx conflicts with our decision on httpRange-14
NDW: namespace names interact with deployed RDDL...
DanC: well, not necessarily the RDF output
NDW: right
DanC: so W3C namespace policy... could we have a W3C REC for RDDL that endorses?
<ht> After some effort, hst concludes that norm's rddl1 example is identical the the existing XMLSchema namespace document plus GRDDL link, so, I will edit in those changes so the namespace doc't can be used for testing . . .
TimBL: ah... hmm... we'd need
assurance that rddl.org has similar policies as w3.org; e.g.
that if they go poof W3C could take it over.
... not sure that's existing W3C policy yet
<DanC_> URIs for W3C Namespaces
<Norm> Note, ht, that my grddl XSL stylesheet has no normative weight so I think it may be premature to add it to the official Schema namespace
<ht> RDDL has no normative weight, but it's been at the namespace URI for years!
<Norm> Fair enough
<ht> All this stuff is there to encourage experimentation, IMHO
"For Recommendation Track documents, the persistence policy for the namespace MUST use the template shown below."
several: seems quite reasonable to keep rddl.org in the namespace name, though yes, W3C policy as written conflicts with that so far.
VQ: this reminds me of "Tim to provide a draft of new namespace policy doc" action from
TimBL: yes, that's in progress...
<timbl_> Ian's latest draft
v 1.25 2005/08/18 15:08:07
TimBL: see esp new material in 4. Namespace Changes over Time
<Zakim> DanC, you wanted to say I think I'm in sync with ndw's draft on ns8
DanC: I wonder about depending on other than text/html ...
<DanC_> GRDDL namespace doc, which is XHTML 1.x
HT: RDDL 1.0 supports DTD-based validation...
DanC: I could do class/rel stuff ala microformats... with relax-ng if you like
NDW: JB suggests RDDL 1.0 or the attribute-based thing...
HT: if we have the GRDDL wildcard, do we need another RDDL dialect besides 1.0?
DanC: no
<Ed> Ed agrees.. we dont need 2.0
NDW: so RDDL 1.0, or other human-readable with GRDDL [that's what I wanted to hear; not sure that's what he said]
<scribe> ACTION: DanC to draft a section on using XHTML 1.x (not RDDL) with GRDDL and relax-ng [recorded in]
<scribe> ACTION: NDW to follow-up on namespaceDocument-8, based on DanC's vanilla XHTML example [recorded in]
VQ: plan to close at the ftf? or take more time?
NDW: well, provided we get the writing and the feedback, let's try to close it. but there's considerable risk in that schedule
DanC: yeah.
<timbl_> Ian's latest draft
v 1.25 2005/08/18 15:08:07
<scribe> ACTION: Tim to provide a draft of new namespace policy doc [CONTINUES] [recorded in]
no news on David Orchard to contextualize his scenarios ...
<scribe> ACTION: David Orchard to contextualize his scenarios, such as more on what is happening with SOAP and WSDL. [CONTINUES] [recorded in]
VQ: done? HT: prepare abstractComponentRefs materials for ftf discussion
HT: that was for the previous
[June] ftf
... hmm... I need to check back with the XML Schema WG about pointing to the p element, but as for this action, pls consider it closed.
VQ: very well
<scribe> ACTION: HT to prepare abstractComponentRefs materials for ftf discussion [DONE] [recorded in]
<DanC_> httpRange-14
DC: httpRange-14 isn't closed in the issues list...
VQ: yes, that's straightforward for me to fix
<Norm> proposed errata
<Zakim> DanC, you wanted to ask that we please don't maintain errata numbers other than information in the message, e.g. message-ids, subjects, dates
DC: in particular, I don't want a state in between "message made it to the archive" and "request is in our queue".
<Norm> ACTION: Norm to find better numbers for the errata [recorded in]
PROPOSED: to acknowledge that Typo in Status , Typo in Status, Missing anchor messages report actual problems
so RESOLVED.
<Norm> ACTION: Norm ot produce an erratum document [recorded in]
<ht> I note that the Schema WG has agreed that they will distinguish between errata and corrigenda, henceforth | http://www.w3.org/2005/08/30-tagmem-minutes | CC-MAIN-2014-52 | refinedweb | 1,369 | 65.42 |
Monks
A while ago I tried to register the CPAN module namespace RHP by filling out the form at. I never got a response, although after some searching I saw that my submission made it onto the modules@perl.org list and ADAMK had responded asking what RHP meant (Red Hot Penguin). I tried to send a response to modules@perl.org including the message I found on the web archive, but never got a response.
So what's the deal with registering module namespaces? Is there a secret to getting on the modules@perl.org list so I can respond to questions like that?
UPDATE - getting downvoted to oblivion here :) Sorry if I am posing a question that wastes people's time, but I did put in a fair amount of due diligence initially. Hopefully this post will help someone out in the future who had the same questions as myself.
From what I understand you wrote a variant of Time::HiRes and you want to call it RHP::Timer where RHP is what you call yourself on the internet. Naming a CPAN module after who wrote it both undescriptive and confusing.
A little searching brought me
here:
2.5.
This name should be as descriptive, accurate and complete as possible. Avoid any risk of ambiguity. Always try to use two or more whole words. Generally the name should reflect what is special about what the module does rather than how it does it.
I thought about using a subset of the Time::HiRes namespace, but at the time I wrote the module it was really for my specific needs and I wasn't sure if it was worthy of the Time::HiRes namespace :)
I've seen arguments flare up before in cases like that (i.e. Tiny), so I decided to take what I thought was the safe route and give it a namespace indicating it was something built for my custom needs rather than general usage - figured that if it gained any traction I could always rename it under the T::H namespace.
This sounds personal. I too have my own personal customized fluffy pillow code. I have a good bit of it, actually. Class, Class2, CLI, DEBUG, Dev...
If I know in my little heart that the code is so specified, so me, so... That I just drop it under my own personal non registered namespace.
I use my cpan handle as my top level namespace. And I don't ask to register the name with cpan. Having a personal, 'yourcode' module and registering the namespace on cpan is an oxymoron.
The whole idea of putting stuff up there is so others can use it. If you have something 'you'- then others can't really directly use it, or wouldn't choose to, would they? That doesn't sound like module stuff, that sounds like script implementation level material- or config file realm.
If you have customizations, maybe it should be controlled by a script or config file instead- to be worthy of a cpan namespace registration.
I'm not entirely sure why brian d foy and others put up with people like me posting quasi-junk such as 'personal'-ish code.
Maybe in hopes that it's actually helpful in other things we do that would very much be used by others.
I use my CPANHANDLE:: modules in projects others may use. But I am not presumptive to imagine other developers would
want to use my variations of Getopt::Std - ones that hard code that the option flag '-d' means debug is on.
I think it's pretty safe to drop it under your cpan handle, who else would want to use an ugly ass namespace like LEOCHARRE:: to register stuff in. (PHRED actually sounds kinda coooool.. maybe I'll write a namespace suggestion module and name it PHRED, and register it on cpan.)
(I hope you don't feel proprietary over the namespace, as in it should be signed by me, that would be childish. Just write your name twice in the AUTHOR pod section instead! :-)
Hope some of that helps. :)
I may get downvoted for this, but so be it...
Don't waste your time with module registration, it is pretty much made irrelevant now by search.cpan.org (yes, the search sucks, but that is another issue entirely). It seems to me that the only reason for registering your module back in the day was so that it got into the "short list" and hopefully then would be more easily found. Nowadays it seems that modules@perl.org is not very well monitored (no offense @guys_who_monitor_the_list, not saying your slacking, just that you have better stuff to do), and is really only useful if you want help finding a better name for your module.
IMO one of the key reason for CPANs success is the fact there is no barrier for upload beyond needing to get a PAUSE account, and basically the anarchy works. Of course this means we also have lots of crap on CPAN, but so what, sometimes there is a gem buried in some of those lumps of crap. The assumption that if you put a kind of virtual bouncer at the door and have them pick and choose what is good and what is bad is just silly, that would only serve to make CPAN look like that persons idea of good code and discourage people who don't want to waste time arguing. If you want opinionated software, the Ruby On Rails guys down the hall will gladly serve you a big glass of kool-aid.
So, assuming you put in a "fair amount of due diligence", then you should just upload your module to CPAN and bypass registration all together. Personally I have over 50 modules and none of them are registered, cause I would rather hack on code then send emails :)
Anyway, enough perlmonks, time to go write code :). | http://www.perlmonks.org/?node_id=684093 | CC-MAIN-2017-17 | refinedweb | 994 | 70.43 |
Transaction IDs in DB2
Retrieve a unique identifier for a unit of work from the DB2 log records
Normally, an application that talks to a database server does not need to be aware of the internals of the database engine with respect to transaction handling. The application issues a series of SQL statements - such as INSERT, UPDATE, DELETE, SELECT, or CREATE TABLE - and at the end of a transaction, a transaction-ending statement is run, either COMMIT or ROLLBACK. A COMMIT statement ends the transaction and tells the database server to make all changes permanent. A ROLLBACK, on the other hand, causes the database server to undo all changes made in the transaction.
The world does not consist of only "normal" applications. Many specialized applications exist, and such applications usually have very specific requirements. For example, an application that is concerned with replicating data from one database system to another, such as DB2 Replication [2], needs to know about transactional information. When replicating data changes, it is usually necessary to replicate all changes made in a single transaction together. Thus, it is necessary to know which changes were made in which transaction and each transaction needs to be identified uniquely.
DB2 UDB does not provide a special register or any other direct means to retrieve the identifier of a transaction, which is needed for internal purposes. In the following sections I describe how you can combine several features of DB2 UDB to come up with a transaction identifier. The general idea is to access the log records, which are written by DB2 to ensure recovery of your valuable data in case of a system crash, power outage or hard drive failure. DB2 stores the internal transaction ID in each log record. Some additional setup-steps are performed to trigger a specific log record to be written so that the correct transaction ID is retrieved.
Accessing the Transaction ID
DB2 UDB comes with a great variety of APIs to manage the database system itself. One of these APIs allows you to access the logs records that are written by the database engine during its operation. Log records are written for INSERT, UPDATE, DELETE, REORGANIZE and many other operations that you can issue to modify the data in the tables of your database or to administer the system itself.
Each log record includes in its header a unique identifier for the transaction (encoded in 6 bytes) [3] that triggered the writing of the record. This identifier is needed to guarantee the durability of all database transactions in case of expected or unexpected interruption of the operation, such as a system failure. DB2 maintains that identifier automatically.
The approach takes advantage of the transaction identifier stored in the log record header. We use the log reader API to access the log records and to extract the transaction ID from there. While doing that, keep the following in mind:
- A log record must be written in the current transaction for which we want to determine the requested identifier.
- Given that a single log (possibly split into several files) is used by the database engine for all concurrent transactions, many or all of which could make data modifications and cause log records to be written concurrently, it is necessary to find a log record that really belongs to the current transaction.
Both issues can be addressed together. We use the DB2-builtin function
GENERATE_UNIQUE to generate a unique value. That value is inserted into a table, causing a log record to be written. In the next step, all new log records (since before the INSERT) are read until the one log record is found that contains the unique value. That's the log record we seek and the transaction ID is extracted from it. Finally, the insert operation is undone so that the table does not accumulate stale data. The whole processing is illustrated in Figure 1.
Figure 1. Logic to extract the transaction identifier from the database log
Implementing the stored procedure
The complete logic outlined above is encapsulated in a single stored procedure. That way, all applications have a simple and standardized way to retrieve the transaction ID. No direct calls to the DB2 API will be necessary. The transaction ID is returned by the stored procedure as a string, that is, a value of type CHAR(12).
Before you can compile the stored procedure you need to create a table named
TA_ID_FORCE_LOGWRITE. This table is accessed inside the procedure. The table itself has a very simple structure consisting of a single column where the unique value generated by the function
GENERATE_UNIQUE, is stored. Create the table using the SQL statement shown in Listing 1:
Listing 1. Creating the table TA_ID_FORCE_LOGWRITE
CREATE TABLE ta_id_force_logwrite ( unique_val VARCHAR(18) FOR BIT DATA NOT NULL, CONSTRAINT taid_pk PRIMARY KEY (unique_val) )@
The procedure is implemented in C++ to access the asynchronous read log API [4], and it uses embedded SQL to perform the necessary SQL operations. A savepoint is used to roll back the INSERT operation that is performed inside the procedure to trigger a log record being written. The SQL statements in the procedure take advantage of the power of SQL supported by DB2 UDB Version 8.2.
Therefore, we generate the unique value, insert it in a table and retrieve it to the stored procedure code all in a single statement. This is done in the section set in italics in the listing below. If you want to use the procedure on an earlier version of DB2, you might have to break this logic into several, independent SQL statements.
The DB2 log is read using the API
db2ReadLog. At the beginning, the API is called to determine the current log sequence number (LSN). This step is done to avoid querying any log records that were written prior to the invocation of the procedure. After all, we are only interested in a single log record: the one written by the INSERT operation.
After the INSERT operation, all new log records are retrieved. For each log record, we verify that it is a log record written for an INSERT operation. If it is and if the data that is inserted contains the unique value used during the INSERT statement, then we have found the log record in question and can return the proper transaction identifier.
Before leaving the procedure, we rollback the processsing to the savepoint that was set at the beginning. Thus, no data modifications remain beyond the scope of the procedure.
The complete code for the procedure is shown in Listing 2. The calls to the log API are set in bold and the SQL statements appear in italics in the listing. The other pieces are only concerned with the preparation of the parameters.
Listing 2. Stored procedure code
#include <string.h> // memset(), memcpy(), strncpy() #include <stdio.h> // sprintf() #include <sqludf.h> #include <db2ApiDf.h> #if defined(__cplusplus) extern "C" #endif int SQL_API_FN getTransactionId( SQLUDF_VARCHAR *taId, SQLUDF_NULLIND *taId_ind, SQLUDF_TRAIL_ARGS) { SQL_API_RC rc = SQL_RC_OK; struct sqlca sqlca; db2ReadLogInfoStruct logInfo; db2ReadLogStruct logData; SQLU_LSN startLsn; SQLU_LSN endLsn; char buffer[64 * 1024] = { '\0' }; // for log record data EXEC SQL BEGIN DECLARE SECTION; char uniqueVal[13] = { '\0' }; EXEC SQL END DECLARE SECTION; // we assume NULL return *taId_ind = -1; /* * Step 1: Set a savepoint to be able to undo the data modifications */ EXEC SQL SAVEPOINT get_transaction_id ON ROLLBACK RETAIN CURSORS; /* * Step 2: Query the DB2 Log to get the start LSN */ memset(&sqlca, 0x00, sizeof sqlca); memset(&logInfo, 0x00, sizeof logInfo); memset(&logData, 0x00, sizeof logData); logData.iCallerAction = DB2READLOG_QUERY; logData.piStartLSN = NULL; logData.piEndLSN = NULL; logData.poLogBuffer = NULL; logData.iLogBufferSize = 0; logData.iFilterOption = DB2READLOG_FILTER_OFF; logData.poReadLogInfo = &logInfo; rc = db2ReadLog(db2Version810, &logData, &sqlca); if (rc < 0) { memcpy(SQLUDF_STATE, "38TA0", SQLUDF_SQLSTATE_LEN); strncpy(SQLUDF_MSGTX, "Could not query log for last LSN", SQLUDF_MSGTEXT_LEN); goto exit; } else if (sqlca.sqlcode) { memcpy(SQLUDF_STATE, "38TA1", SQLUDF_SQLSTATE_LEN); snprintf(SQLUDF_MSGTX, SQLUDF_MSGTEXT_LEN, "SQL error while " "reading log records. SQLCODE = %d, SQLSTATE=%s", sqlca.sqlcode, sqlca.sqlstate); goto exit; } memcpy(&startLsn, &logInfo.nextStartLSN, sizeof startLsn); /* * Step 3: Force a log record to be written * * Insert a unique value into our table, which triggers a log record to be * written. The same value is also returned right away so that we can use * it to search through the new log records. */ EXEC SQL SELECT value INTO :uniqueVal FROM NEW TABLE ( INSERT INTO ta_id_force_logwrite VALUES ( GENERATE_UNIQUE() ) ) AS t(value); if (sqlca.sqlcode) { memcpy(SQLUDF_STATE, "38TA2", SQLUDF_SQLSTATE_LEN); snprintf(SQLUDF_MSGTX, SQLUDF_MSGTEXT_LEN, "SQL error while " "triggering log record. SQLCODE = %d, SQLSTATE=%s", sqlca.sqlcode, sqlca.sqlstate); goto exit; } /* * Step 4: Search through the new log records to find our INSERT */ while (true) { char *ptr = NULL; char *transactionId = NULL; sqlint32 recordLength = 0; memset(&sqlca, 0x00, sizeof sqlca); memset(&logInfo, 0x00, sizeof logInfo); memset(&logData, 0x00, sizeof logData); memset(&endLsn, 0xFF, sizeof endLsn); logData.iCallerAction = DB2READLOG_READ_SINGLE; logData.piStartLSN = &startLsn; logData.piEndLSN = &endLsn; logData.poLogBuffer = buffer; logData.iLogBufferSize = sizeof buffer; logData.iFilterOption = DB2READLOG_FILTER_OFF; logData.poReadLogInfo = &logInfo; rc = db2ReadLog(db2Version810, &logData, &sqlca); if (rc < 0) { memcpy(SQLUDF_STATE, "38TA3", SQLUDF_SQLSTATE_LEN); sprintf(SQLUDF_MSGTX, "Could not read log record. rc = %d", (int)rc); goto exit; } else if (sqlca.sqlcode == SQLU_RLOG_READ_TO_CURRENT) { memcpy(SQLUDF_STATE, "38TA4", SQLUDF_SQLSTATE_LEN); strncpy(SQLUDF_MSGTX, "Last log record reached prematurely.", SQLUDF_MSGTEXT_LEN); goto exit; } else if (sqlca.sqlcode) { memcpy(SQLUDF_STATE, "38TA5", SQLUDF_SQLSTATE_LEN); snprintf(SQLUDF_MSGTX, SQLUDF_MSGTEXT_LEN, "SQL error while " "reading log records. SQLCODE = %d, SQLSTATE=%s", sqlca.sqlcode, sqlca.sqlstate); goto exit; } if (logInfo.logBytesWritten < 20) { memcpy(SQLUDF_STATE, "38TA6", SQLUDF_SQLSTATE_LEN); strncpy(SQLUDF_MSGTX, "Log Manager Header of record too small.", SQLUDF_MSGTEXT_LEN); goto exit; } memcpy(&startLsn, &logInfo.nextStartLSN, sizeof startLsn); // the data in the buffer starts with the LSN, followed by the Log // Manager Header; skip the LSN ptr = buffer; ptr += sizeof(SQLU_LSN); // get the length of the log record (plus LSN) recordLength = *(sqlint32 *)ptr + sizeof(SQLU_LSN); ptr += 4; // verify that this is a "Normal" log record if (*(sqlint16 *)ptr != 0x004E) { continue; } ptr += 2; // skip behind the Log Manager Header (to the DMS Log Record Header); // (we do not have "Compensation" records here and "Propagatable" // doesn't occur either) ptr += 2 + // flags 6; // LSN of previous record in same transaction // remember the location of the transaction id transactionId = ptr; ptr += 6; // now we are at the beginning of the DML Log Record Header if (ptr - buffer + 18 + 4 > recordLength) { continue; } // check that the "Function identifier" in the DMS header indicates an // "INSERT" log record ptr += 1; if (*(unsigned char *)ptr != 118) { continue; } // skip to the record data ptr += 5 + // remainder of DMS Log Record Header 2 + // padding 4 + // RID 2 + // record Length 2 + // free space 2; // record offset // the record contains data if the 1st byte of the record header (the // record type) is 0x00 or 0x10, or if the bit 0x04 is set if (*ptr != 0x00 && *ptr != 0x10 && (*ptr & 0x04) == 0) { continue; } ptr += 4; // we reached the record data and the unique value can be found after // the record length ptr += 1 + // record type 1 + // reserved 2 + // length of fixed length data 4; // RID // that's where the unique value should be // once we found the unique value, extract the transaction ID and // convert it to a string if (memcmp(ptr, uniqueVal, 13) == 0) { int i = 0; char *result = taId; for (i = 0; i < 6; i++) { sprintf(result, "%02hhx", ptr[i]); result += 2; } *result = '\0'; *taId_ind = 0; break; // found the correct log record } } exit: EXEC SQL ROLLBACK TO SAVEPOINT get_transaction_id; return SQLZ_DISCONNECT_PROC; }
The stored procedure can be compiled with the
bldrtn script that can be found in the
sqllib/samples/c/ directory. That script generates a shared library and that library is copied to the
sqllib/function directory. Once this is done you can register the procedure in your database as shown in Listing 3. This is the final step before you can start using the procedure.
Listing 3. Register the procedure in the database
CREATE PROCEDURE getTransactionId ( OUT transactionId CHAR(12) ) SPECIFIC getTaId DYNAMIC RESULT SETS 0 MODIFIES SQL DATA NOT DETERMINISTIC NEW SAVEPOINT LEVEL LANGUAGE C EXTERNAL NAME 'transaction-id!getTransactionId' FENCED THREADSAFE NO EXTERNAL ACTION PARAMETER STYLE SQL PROGRAM TYPE SUB NO DBINFO@
Testing the procedure
The final step is to verify the proper functioning of the procedure. Listing 4 shows some SQL statements that were executed on the DB2 command line with auto-commit turned off. The very first scenario illustrates the error that you will get if you still have circular logging activated. Following that, you will see the results of various calls to the stored procedure with some data modifications thrown in. Of course, DB2 will only assign a new transaction ID after a COMMIT or ROLLBACK has been executed, and only if the current transaction already caused log records to be written.
Listing 4. Testing the procedure
$ db2 -c- -td@ db2 => CALL getTransactionId(?)@ SQL0443N Routine "*ACTIONID" (specific name "") has returned an error SQLSTATE with diagnostic text "SQL error while reading log records. SQLCODE = -2651, SQLS". SQLSTATE=38TA1 db2 => ? sql2651@ SQL2651N The log records associated with the database can not be asynchronously read. Explanation: The asynchronous read log API was used against a connected database which does not have LOG RETAIN or USER EXITS ON. Only databases which are forward recoverable may have their associated logs read. User Response: Update the database configuration for the database, identified to the asynchronous read log API, turning LOG RETAIN and/or USER EXITS ON. db2 => UPDATE DATABASE CONFIGURATION USING LOGRETAIN ON@ db2 => BACKUP DATABASE sample TO /dev/null@ Backup successful. The timestamp for this backup image is : 20050305214103 db2 => TERMINATE@ $ db2stop force && db2start && db2 -c- -td@ db2 => CONNECT TO sample@ db2 => CALL getTransactionId(?)@ Value of output parameters -------------------------- Parameter Name : TRANSACTIONID Parameter Value : 200503052054 Return Status = 0 db2 => COMMIT@ DB20000I The SQL command completed successfully. db2 => CALL getTransactionId(?)@ Value of output parameters -------------------------- Parameter Name : TRANSACTIONID Parameter Value : 200503052054 Return Status = 0 db2 => CREATE TABLE t ( a INT )@ DB20000I The SQL command completed successfully. db2 => CALL getTransactionId(?)@ Value of output parameters -------------------------- Parameter Name : TRANSACTIONID Parameter Value : 200503052055 Return Status = 0 db2 => ROLLBACK@ DB20000I The SQL command completed successfully. db2 => CALL getTransactionId(?)@ Value of output parameters -------------------------- Parameter Name : TRANSACTIONID Parameter Value : 200503052056 Return Status = 0
Conclusion
There are many reasons why a DBA might want to be able to identify the current unit of work, for example, when managing a replication process. Using the technique I've described here, you can take advantage of DB2 UDB's unique capabilities and increase your knowledge of what's going on "under the covers" in your database.
Downloadable resources
- PDF of this content
- Stored procedure to retrieve the transaction ID (transaction-id.zip | 4 KB)
Related topics
- [1] You can find the DB2 UDB manuals online.
- [2] DB2 SQL Replication and DB2 Q Replication are tools to replicate data from one database system to another.
- [3] The structure of the DB2 UDB Log Records is described here.
- [4] Documentation of the Asynchronous Log Reader API. | https://www.ibm.com/developerworks/data/library/techarticle/dm-0505stolze2/index.html | CC-MAIN-2019-39 | refinedweb | 2,465 | 52.7 |
Android phones have been growing ever more powerful with time, with the Nexus 5 sporting a quad-core 2.3 GHz Krait 400; this is a very powerful CPU for a mobile phone. With most Android apps being written in Java, does Java allow us to access all of that power? Or, put another way, is Java efficient enough, allowing tasks to complete more quickly and allowing the CPU to idle more, saving precious battery life?
(Note: An updated version of this comparison is available at A Performance Comparison Redux: Java, C, and Renderscript on the Nexus 5, along with source code).
In this post, I will take a look at a DSP filter adapted from coefficients generated with mkfilter, and compare three different implementations: one in C, one in Java, and one in Java with some manual optimizations. The source for these tests can be downloaded at the end of this post.
To compare the results, I ran the filter over an array of random data on the Nexus 5, and the compared the results to the fastest implementation. In the following table, a lower runtime is better, with the fastest implementation getting a relative runtime of 1.
The statically-compiled C code gave the best execution times, followed by ART and then by Dalvik. The C code uses JNI via
GetShortArrayRegion and
SetShortArrayRegion to marshal the data from Java to C, and then back from C to Java once processing has completed.
The best performance came courtesy of GCC 4.8, with little variation between the different additional optimization options. Clang’s ARM builds are not quite as optimized as GCC’s; toggling LOCAL_ARM_NEON := true in the NDK makefile also makes a clear difference in performance.
Even the slowest native build using clang is not more than 43% slower than the best native build using gcc. Once we switch to Java, the variance starts to increase significantly, with the best runtime about 2.2x slower than native code, and the worst runtime a staggering 17.8x slower.
What explains the large difference? For one, it appears that both ART and Dalvik are limited in the amount of static optimizations that they are capable of. This is understandable in the case of Dalvik, since it uses a JIT and it’s also much older, but it is disappointing in the case of ART, since it uses ahead-of-time compilation.
Is there a way to speed up the Java code? I decided to try it out, by applying the same static optimizations I would have expected the compiler to do, like converting modulo to bit masks and inlining function calls. These changes resulted in one massive and hard to read function, but they also dramatically improved the runtime performance, with Dalvik speeding up from a 17.8x penalty to 2.9x, and ART speeding up from an 8.0x penalty to 2.2x.
The downside of this is that the code has to be abused to get this additional performance, and it still doesn’t come close to matching the ahead-of-time code generated by gcc and clang, which can surpass that performance without similar abuse of the code. The NDK is still a viable option for those looking for improved performance and more efficient code which consumes less battery over time.
Just for fun, I decided to try things out on a laptop with a 2.6 GHz Intel Core i7. For this table, the relative results are in the other direction, with 1x corresponding to the best time on the Nexus 5, 2x being twice as fast, and so on. The table starts with the best results first, as before.
As on the Nexus 5, the C code runs faster, but to Java’s credit, the gap between the best & worst result is less than 4x, which is much less variance than we see with Dalvik or ART. Java 1.6 and 1.7 are very close to each other, unless “-XX:+AggressiveOpts” is used; with that option enabled, 1.7 is able to pull ahead.
There is still an unfortunate gap between the “normal” code and the manually-optimized code, which really should be closable with static analysis and inlining.
The other interesting result is that the gap between mobile and PC is closing over time, and even more so if you take power consumption into account. It’s quite impressive to see that as far as single-core performance goes, the PC and smartphone are closer than ever.
Conclusion
Recent Android devices are getting very powerful, and with the new ART runtime, common Java code can be executed quickly enough to keep user interfaces responsive and users happy.
Sometimes, though, we need to go further, and write demanding code that needs to run quickly and efficiently. With the latest Android devices, these algorithms may be able to run quickly enough in the Dalvik VM or with ART, but then we have to ask ourselves: is the benefit of using a single language worth the cost of lower performance? This isn’t just an academic question: lower performance means that we need to ask our users to give us more CPU cycles, which shortens their device’s battery life, heats up their phones, and makes them wait longer for results, and all because we didn’t want to write the code in another language.
For these reasons, writing some of our code in C/C++, FORTRAN, or another native language can still make a lot of sense.
For more reading on this topic, check out How Powerful is Your Nexus 7?
Source
dsp.c
#include "dsp.h" #include <algorithm> #include <cstdint> #include <limits> static constexpr int int16_min = std::numeric_limits<int16_t>::min(); static constexpr int int16_max = std::numeric_limits<int16_t>::max(); static inline int16_t clamp(int input) { return std::max(int16_min, std::min(int16_max, input)); } static inline int get_offset(const FilterState& filter_state, int relative_offset) { return (filter_state.current + relative_offset) % filter_state.size; } static inline void push_sample(FilterState& filter_state, int16_t sample) { filter_state.input[get_offset(filter_state, 0)] = sample; ++filter_state.current; } static inline int16_t get_output_sample(const FilterState& filter_state) { return clamp(filter_state.output[get_offset(filter_state, 0)]); } static inline void apply_lowpass(FilterState& filter_state) { double* x = filter_state.input; double* y = filter_state.output; y[get_offset(filter_state, 0)] = ( 1.0 * (1.0 / 6.928330802e+06) * (x[get_offset(filter_state, -10)] + x[get_offset(filter_state, -0)])) + ( 10.0 * (1.0 / 6.928330802e+06) * (x[get_offset(filter_state, -9)] + x[get_offset(filter_state, -1)])) + ( 45.0 * (1.0 / 6.928330802e+06) * (x[get_offset(filter_state, -8)] + x[get_offset(filter_state, -2)])) + (120.0 * (1.0 / 6.928330802e+06) * (x[get_offset(filter_state, -7)] + x[get_offset(filter_state, -3)])) + (210.0 * (1.0 / 6.928330802e+06) * (x[get_offset(filter_state, -6)] + x[get_offset(filter_state, -4)])) + (252.0 * (1.0 / 6.928330802e+06) * x[get_offset(filter_state, -5)]) + ( -0.4441854896 * y[get_offset(filter_state, -10)]) + ( 4.2144719035 * y[get_offset(filter_state, -9)]) + ( -18.5365677633 * y[get_offset(filter_state, -8)]) + ( 49.7394321983 * y[get_offset(filter_state, -7)]) + ( -90.1491003509 * y[get_offset(filter_state, -6)]) + ( 115.3235358151 * y[get_offset(filter_state, -5)]) + (-105.4969191433 * y[get_offset(filter_state, -4)]) + ( 68.1964705422 * y[get_offset(filter_state, -3)]) + ( -29.8484881821 * y[get_offset(filter_state, -2)]) + ( 8.0012026712 * y[get_offset(filter_state, -1)]); } void apply_lowpass(FilterState& filter_state, const int16_t* input, int16_t* output, int length) { for (int i = 0; i < length; ++i) { push_sample(filter_state, input[i]); apply_lowpass(filter_state); output[i] = get_output_sample(filter_state); } }
dsp.h
#include <cstdint> struct FilterState { static constexpr int size = 16; double input[size]; double output[size]; unsigned int current; FilterState() : input{}, output{}, current{} {} }; void apply_lowpass(FilterState& filter_state, const int16_t* input, int16_t* output, int length);
Here is the Java adaptation of the C code:
package com.example.perftest; import com.example.perftest.DspJavaManuallyOptimized.FilterState; public class DspJava { public static class FilterState { static final int size = 16; final double input[] = new double[size]; final double output[] = new double[size]; int current; } static short clamp(short input) { return (short) Math.max(Short.MIN_VALUE, Math.min(Short.MAX_VALUE, input)); } static int getOffset(FilterState filterState, int relativeOffset) { return ((filterState.current + relativeOffset) % FilterState.size + FilterState.size) % FilterState.size; } static void pushSample(FilterState filterState, short sample) { filterState.input[getOffset(filterState, 0)] = sample; ++filterState.current; } static short getOutputSample(FilterState filterState) { return clamp((short) filterState.output[getOffset(filterState, 0)]); } static void applyLowpass(FilterState filterState) { final double[] x = filterState.input; final double[] y = filterState.output; y[getOffset(filterState, 0)] = ( 1.0 * (1.0 / 6.928330802e+06) * (x[getOffset(filterState, -10)] + x[getOffset(filterState, -0)])) + ( 10.0 * (1.0 / 6.928330802e+06) * (x[getOffset(filterState, -9)] + x[getOffset(filterState, -1)])) + ( 45.0 * (1.0 / 6.928330802e+06) * (x[getOffset(filterState, -8)] + x[getOffset(filterState, -2)])) + (120.0 * (1.0 / 6.928330802e+06) * (x[getOffset(filterState, -7)] + x[getOffset(filterState, -3)])) + (210.0 * (1.0 / 6.928330802e+06) * (x[getOffset(filterState, -6)] + x[getOffset(filterState, -4)])) + (252.0 * (1.0 / 6.928330802e+06) * x[getOffset(filterState, -5)]) + ( -0.4441854896 * y[getOffset(filterState, -10)]) + ( 4.2144719035 * y[getOffset(filterState, -9)]) + ( -18.5365677633 * y[getOffset(filterState, -8)]) + ( 49.7394321983 * y[getOffset(filterState, -7)]) + ( -90.1491003509 * y[getOffset(filterState, -6)]) + ( 115.3235358151 * y[getOffset(filterState, -5)]) + (-105.4969191433 * y[getOffset(filterState, -4)]) + ( 68.1964705422 * y[getOffset(filterState, -3)]) + ( -29.8484881821 * y[getOffset(filterState, -2)]) + ( 8.0012026712 * y[getOffset(filterState, -1)]); } public static void applyLowpass(FilterState filterState, short[] input, short[] output, int length) { for (int i = 0; i < length; ++i) { pushSample(filterState, input[i]); applyLowpass(filterState); output[i] = getOutputSample(filterState); } } }
Since all of the Java runtimes tested don’t exploit static optimization opportunities as well as it seems that they could, here is an optimized version that has been inlined and has the modulo replaced with a bit mask:
package com.example.perftest; public class DspJavaManuallyOptimized { public static class FilterState { static final int size = 16; final double input[] = new double[size]; final double output[] = new double[size]; int current; } public static void applyLowpass(FilterState filterState, short[] input, short[] output, int length) { for (int i = 0; i < length; ++i) { filterState.input[(filterState.current + 0) & (FilterState.size - 1)] = input[i]; ++filterState.current; final double[] x = filterState.input; final double[] y = filterState.output; y[(filterState.current + 0) & (FilterState.size - 1)] = ( 1.0 * (1.0 / 6.928330802e+06) * (x[(filterState.current + -10) & (FilterState.size - 1)] + x[(filterState.current + -0) & (FilterState.size - 1)])) + ( 10.0 * (1.0 / 6.928330802e+06) * (x[(filterState.current + -9) & (FilterState.size - 1)] + x[(filterState.current + -1) & (FilterState.size - 1)])) + ( 45.0 * (1.0 / 6.928330802e+06) * (x[(filterState.current + -8) & (FilterState.size - 1)] + x[(filterState.current + -2) & (FilterState.size - 1)])) + (120.0 * (1.0 / 6.928330802e+06) * (x[(filterState.current + -7) & (FilterState.size - 1)] + x[(filterState.current + -3) & (FilterState.size - 1)])) + (210.0 * (1.0 / 6.928330802e+06) * (x[(filterState.current + -6) & (FilterState.size - 1)] + x[(filterState.current + -4) & (FilterState.size - 1)])) + (252.0 * (1.0 / 6.928330802e+06) * x[(filterState.current + -5) & (FilterState.size - 1)]) + ( -0.4441854896 * y[(filterState.current + -10) & (FilterState.size - 1)]) + ( 4.2144719035 * y[(filterState.current + -9) & (FilterState.size - 1)]) + ( -18.5365677633 * y[(filterState.current + -8) & (FilterState.size - 1)]) + ( 49.7394321983 * y[(filterState.current + -7) & (FilterState.size - 1)]) + ( -90.1491003509 * y[(filterState.current + -6) & (FilterState.size - 1)]) + ( 115.3235358151 * y[(filterState.current + -5) & (FilterState.size - 1)]) + (-105.4969191433 * y[(filterState.current + -4) & (FilterState.size - 1)]) + ( 68.1964705422 * y[(filterState.current + -3) & (FilterState.size - 1)]) + ( -29.8484881821 * y[(filterState.current + -2) & (FilterState.size - 1)]) + ( 8.0012026712 * y[(filterState.current + -1) & (FilterState.size - 1)]); output[i] = (short) Math.max(Short.MIN_VALUE, Math.min(Short.MAX_VALUE, (short) filterState.output[(filterState.current + 0) & (FilterState.size -.
50 thoughts on “A performance comparison between Java and C on the Nexus 5”
How fast was Renderscript? That’s the recommended way to write this type of code on Android. It should automatically parallelize, so up to 4 times faster than your c code.
I tried porting the code to Renderscript, but I don’t have experience using Renderscript and I didn’t succeed in getting it to work. If you have an implementation I can plug in and test, I’d be glad to add it to the comparison.
Did you consider using Proguard to optimize je Java code and see how the results are affected?
It is included in the Android SDK – but not all the optimizations are enabled by default.
I didn’t try it, but I’m not sure how much of a difference it would make on code that is run through a JIT / AOT compiler. I agree it’s worth a shot, and I can try it in a future update.
Proofread your article.
> with the Nexus 5 sporting a auad-core
Fixed, thanks. 🙂
Not very interesting since 95% of code is just Gluing gui and IO together.
Also your comparison probably does not ensure that the JIT kicked in.
“Not very interesting since 95% of code is just Gluing gui and IO together.”
Well, your experiences and opinions are not necessarily representative of everyone else’s. 🙂
“Also your comparison probably does not ensure that the JIT kicked in.”
How much time does the JIT need before it can “kick in”? 1 minute? 5 minutes? 30 minutes? ART also uses ahead-of-time compilation.
Is there a performance difference if you mark the java method parameters as final ?
I didn’t try that, but the methods are already static, so I wouldn’t expect a huge difference. I can try it in the next update.
Excellent — thank you
Typo on first line: auad-core
Thank you, just noticed it myself as well. Amazing how many times we can read over something and our brain auto-fills in what we expected to read. 😉
Now, correct me if I’m wrong, being that filterState.current is part of a class, and I’m assuming that the Java compiler would compile that to be located in a contiguous block of memory, wouldn’t you gain a further optimization by pulling filterState.current out into a final loop variable that would be located on the stack, and therefore more temporally favorable, cache wise?
I could be totally off base, but I think it might help if you were to take that out and not get it by referencing through filterState. I’m further supposing that being that this is single threaded, there are no other actors upon this variable, meaning that placing it on the stack, before the matrix calculations, might accomplish something without negative side-affects.
Like I said though, please correct me if I’m wrong.
I was hoping that would be obvious enough for the compilers to do on their own 😉 You’re right, though, this would be good to test out for the “manually-optimized” Java to see if it can speed things up further.
Where is the test driver code? These results are not reproducible without the complete source.
The test driver code is quite simple so I didn’t want to lengthen the post by posting it here since it can easily be reproduced; if there’s enough demand, I’ll clean it up and post it.
Sorry, I call complete bullshit. Once a JIT compiles a repeated section of code, it is comparable with native, and this is the most important point. Your code does not have as many code paths as you think ever.
If java can new an object faster than malloc, (which it can and does), and the JIT can outrun native code which cannot self-optimize, why are your numbers off? Because these are bullshit tests
JITs have a set of compromises, both inherent in the safety guarantees and semantics of the language and in the time spent on optimization. If you really feel that this is bullshit, the algorithm implementations are there; please feel free to publish your own results. I’m not really vested in the results either way, just thought I had something interesting to share.
Might be worth trying to replace Max / Min calls with ‘if’ statement to eliminate function call overheads.
When I tried that, it made no difference, so I believe that they are being replaced with intrinsics.
To take advantage of these performance gains would you you need to write the entire app in C++? Or can you call optimized executable binaries from Java?
The way I’m doing it is by calling C++ from Java via JNI (Java Native Interface), so you can definitely write apps in both languages. With the NDK, your native code gets compiled to a shared library that you can call from Java, and this is also, in fact, how some of Android’s Java APIs are implemented. There are some overhead & gotcha issues to consider, but those can be minimized by reducing the “surface” of the interface between both languages.
Malloc is actually very slow, even slower if your memory is fragmented. Optimizing memory allocation in C is very viable, and depending on the context you can easily outrun malloc if you really wanted to.
At the moment AggressiveOpts doesn’t really do anything which makes me question *why* you got a performance improvement while using it. Also how the results are reported suggests that this was run as a proper set of experiments. I’m don’t really have the time to run these experiments myself to tell you exactly why this benchmark is busted but the result don’t give my any confidence to conclude anything other than this whole exercise smells like a yet another borked micro benchmark.
Why do you say it doesn’t do anything? I’m curious. As for the benchmark, I wasn’t expecting the post to get this much attention! I’ll prepare a follow-up and share the entire project so people can compile it for themselves, and try out alternatives to see if one or the other can be improved.
Thanks for your article. Having written some benchmark related posts myself I’m somewhat biased, but it’s always striking to see what harsh comments are made from well informed and less informed, but not necessarily less harsh, people and how litte the work for such a post is appreciated.
Thank you for the kind words, Stefan! This one definitely stirred up some controversy. 😉 It will be worth doing a follow-up post to try out some of the suggestions made by the commentators.
I work on the Renderscript team and would like to help creating a Renderscript version. Can you send me the complete code?
Hi Jean-Luc, that would be very kind of you guys! I did reply to your email a couple of days ago; hopefully the reply didn’t get lost in spam.
Hey, if you put a Renderscript version, would you please post it here?
Also, can you please put a simple app project (maybe on GitHub) with all of the different tests?
BTW, the code on this article has a lot of “&” written with a prefix (like “&” and “>” ) .
If I don’t hear back from the Google guys about Renderscript by a couple of weeks from now, I’ll just go ahead and move the code to GitHub; that should help out with the ampersand issues that keep coming back. 😉
Some apps have important parts that must be as quick as possible:
games, image/audio/video processing, complex 3d rendering …
So, even if 5% of the code is doing this, the user should not wait so long for the results.
Also, the Dalvik heap is quite restricted in terms of how much MB it can hold, while C/C++ is restricted only to what the device has, which is more than enough in most cases.
I’ve even made a tiny C/C++ library that demostrates it , by allowing you to handle bitmap data, even if it’s quite large :
Definitely agreed! Also, I believe that we can sometimes forget about the other side of the coin — energy & memory usage. More efficiency means that our app is a better citizen on the user’s device, which equals happier users. This doesn’t automatically = NDK, but it also means that it shouldn’t be ruled out, either.
I wonder if Google would still go with the VM solution if they were making a decision today. Apple has shown that there are ways of reducing some of the pain of native programming with technologies like ARC, and the ease of integration between C, Objective C, and C++ on Apple’s platform is something that I envy when writing JNI code using the NDK.
I’m curious about the heap restrictions — is that actually still true on recent versions of Android? I would have expected Google to fix that at some point since it seems like an oversight on their part.
I started working on it today. Sorry, other work had to take priority 🙁 We’re not forgetting you!
No worries! I know how busy you guys can get, so I’m very grateful that you’d be willing to take your time for this. No rush!
An update will be coming soon within the next few weeks, with thanks to Jean-Luc Brouillet for porting the test code to Renderscript! When it’s ready, I’ll release the entire project to GitHub so everyone can tinker with it and explore.
Hi,
you have got a small typo in your dsp.h file:
FilterState() : input{}, output{}, current{} {} => FilterState() : input{}, output{}, current(0) {}
Regards,
Igor.
Hi Igor,
Thanks for the catch; I think I was taking advantage of a C++ feature there. 😉
Sorry but I missed your questions to my response. Why do I say AggressiveOpts doesn’t do anything. The purpose of AggressiveOpts was to create a bag of experimental settings that offered good performance results on Spec benchmarks. As the experimental options matured they became defaults. Here is the current list of AggressiveOpts
// Aggressive optimization flags -XX:+AggressiveOpts
void Arguments::set_aggressive_opts_flags() {
#ifdef COMPILER2
if (AggressiveOpts || !FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
if (FLAG_IS_DEFAULT(EliminateAutoBox)) {
FLAG_SET_DEFAULT(EliminateAutoBox, true);
}
if (FLAG_IS_DEFAULT(AutoBoxCacheMax)) {
FLAG_SET_DEFAULT(AutoBoxCacheMax, 20000);
}
// Feed the cache size setting into the JDK
char buffer[1024];
sprintf(buffer, “java.lang.Integer.IntegerCache.high=” INTX_FORMAT, AutoBoxCacheMax);
add_property(buffer);
}
if (AggressiveOpts && FLAG_IS_DEFAULT(DoEscapeAnalysis)) {
FLAG_SET_DEFAULT(DoEscapeAnalysis, true);
}
if (AggressiveOpts && FLAG_IS_DEFAULT(BiasedLockingStartupDelay)) {
FLAG_SET_DEFAULT(BiasedLockingStartupDelay, 500);
}
if (AggressiveOpts && FLAG_IS_DEFAULT(OptimizeStringConcat)) {
FLAG_SET_DEFAULT(OptimizeStringConcat, true);
}
if (AggressiveOpts && FLAG_IS_DEFAULT(OptimizeFill)) {
FLAG_SET_DEFAULT(OptimizeFill, true);
}
#endif
}
}
Of these, escape analysis is true already as is autoboxing elimination, the autoboxing cache is much bigger here and biased locking delays are shorter. You can use -XX:+PrintFlagsFinal to check the others if you’d like.
Sorry in advance if this sounds harsh, it’s not intended to be so. But, to answer Why do I claim busted? Well it’s configuration and warmup concerns plus with no indication of variance I’d have to run everything myself to gain any confidence in the results. Also you should at a minimum have run with -XX:+PrintCompilation so that you’d understand what was being JIT’ed and more importantly, what wasn’t. How did GC interfere? Simply too many unanswered questions that could radically alter the results. In fact your data demonstrates huge variances with no real explanation as to *why* these huge variances exist. Is there is a variance it means your system was doing something else. What was that something else? Was it a spurious event? Is it an artifact of the test environment or something that is real and needs to be considered?
It can take a lot of time to answer these questions and once you do, you’ll have a gem of a benchmark that can answer useful questions.
I don’t know why but on my PC, Java is faster than C.
How did you measure the runtime speed?
There’s an updated version of this post at, along with source code, if anyone is interested. | http://www.learnopengles.com/a-performance-comparison-between-java-and-c-on-the-nexus-5/ | CC-MAIN-2018-05 | refinedweb | 3,939 | 57.87 |
Ticket #26642 (closed defect: fixed)
opencv 2.1.0 memory leaks
Description
Hi,
I think there must be something wrong with function cvShowImage(). A simple piece of code that plays a video like (see below) just keeps allocating memory all the time. This same program compiled against port opencv 2.0.0 just takes 30 MB and stays around that amount of memory.
code:
#include <stdio.h> #include "highgui.h"
int main(int argc, char* argv[]) {
if (argc != 2) {
printf("%s <file>\n", argv[0]); return -1;
}
cvNamedWindow(title, CV_WINDOW_AUTOSIZE); CvCapture *capture = cvCreateFileCapture(argv[1]); IplImage *frame;
while (1) {
frame = cvQueryFrame(capture); if (!frame)
break;
cvShowImage() posible memory leak... cvShowImage(title, frame); char c = cvWaitKey(33); if (c == 27)
break;
}
cvReleaseCapture(&capture); cvDestroyWindow(title); return 0;
}
If I comment out the line that show the image on screen (cvShowImage()) the behaviour of the memory is right. So I think that maybe something is wrong with this function...
I don't know if this should be reported to the opencv developers... Thanks for the help.
Change History
comment:2 Changed 3 years ago by jmr@…
- Keywords opencv 2.1.0 memory leak removed
- Priority changed from High to Normal
- Cc gonzalo.llorente@… removed
- Owner changed from macports-tickets@… to stante@…
Please remember to cc the maintainer. As per the ticket guidelines, the High priority is reserved for the use of MacPorts team members.
comment:3 Changed 3 years ago by gonzalo.llorente@…
Hi,
This issue has been reported months ago. Someone pointed out a fix ticket in the opencv list.
is this patch applied in latest opencv macport?
regards, gonzalo.
Cc Me! | http://trac.macports.org/ticket/26642 | CC-MAIN-2013-20 | refinedweb | 271 | 68.67 |
A simple control panel for application admins to manage users and privileges using Firebase.
Firebase admin SDK is a server side SDK that allows us to interact with our Firebase project with admin privileges and perform certain actions to monitor and manager our project in our own way without using the Firebase console.
We are going to create a web application through which we will try to perform the actions that the Firebase admin SDK provides us with.
For that purpose we will need a front-end application which will act as the control panel and a back-end where we will integrate the admin SDK.
We will walk-through the front-end in another Part.
This project is made using Ubuntu 20.04 OS.
Pre-requisites
Create a firebase project and turn on Authentication — email & password authentication, and Realtime Database.
Visit console.firebase.com to create a project and configure as above.
Part 1 — Making the back-end
We will be using node-js as the back-end for making a rest API that our front-end application will consume. We will be using Typescript as it provides us a better and error free way to write Javascript code.
In the first step we are going to set up a node project to use Typescript. We will use express for making the rest API.
After creating a new folder and opening the terminal, let’s run the commands to create the project.
npm init -y
Okay, now we have a package.json file. Let’s install the required dependencies for our project.
npm install express cors dotenv firebase-admin
Also typescript , tslint and the type declarations for cors and express as dev-dependencies.
npm install typescript tslint @types/express @types/cors
Now let’s make a few changes to the package.json to really integrate typescript in our build process. We will add a “start” key to the scripts object as follows.
“start”: “tsc && node dist/index.js”
With this we are making sure that we are running the Typescript compiler (or tsc) to transpile all the .ts files before running the application. We will modify the .tsconfig file to mention the dist directory as the output directory for the typescript compiler later in the article.
Let’s mention the “dist/index.js” as the value of the main property as this file will be the entry point for our application.
With these changes, the package.json file should look similar to this.
Now, let’s add a tsconfig.json file to the project root with the following values. This file is a configuration file for typescript specific to that project. Here we mention the “outDir” as “dist” which makes sure that tsc uses the dist directory as the output directory for the transpiled files.
Now to configure Typescript linting for the project, in a terminal running in the root of the project, run the following command to generate tslint.json.
./node_modules/.bin/tslint --init
Open the generated tslint.json file and the no-console rule accordingly.
Now lets start configuring firebase-admin sdk in our project. For initializing the firebase-admin sdk we need to configure a service account.
Follow this guide to configure service account, download the key and rename it as service-key.json. Place this file in the root of the project directory.
This file should not be pushed to any remote location where it is subject to the risk of getting exposed. This file should be added to the .gitignore file in case of git.
In this project we are using dotenv to simplify the task of setting and using environment variables in multiple environments. So, we will create a .env file at the project root to where we can define the several values that we require as environment variables.
Create a .env file and paste the following values:
GOOGLE_APPLICATION_CREDENTIALS=service-key.json DB_URL=<Your DB URL>
Find your DB URL in the firebase console on top of your realtime database.
Now, we will create a directory structure as shown:
src
— models
—modules
— — admin
— — auth
— — users
Create an index.ts file under the src directory.
In the index.ts file, let’s import the required modules.
import express from 'express'; import * as admin from 'firebase-admin'; import * as dotenv from 'dotenv'; import cors from 'cors';
Now, before we initialize the admin sdk, we need to configure dotenv , in order to inject the values mentioned in the .env file as the environment variables.
const dotenvKey = dotenv.config();
Here you can remove the constant assignment as we are not going to use the dotenvKey constant in the project.
Now, to initialize the firebase-admin sdk.
admin.initializeApp({ credential: admin.credential.applicationDefault(), databaseURL: process.env.DB_URL });
Here, firebase-admin will use the environment variable mapped by us in the .env file to access the service-key.json file. Also, we provide the databaseURL as our application will access the realtime database.
Now, let’s add the boilerplate code to create an express app.
**const** port = process.env.PORT || 8080; **const** app = _express_(); app._use_(cors({origin: true})); app._use_(express._json_()); app._use_(express._urlencoded_({extended: false}));
We use cors to avoid the CORS error while consuming endpoints from a browser.
A great thing about Typescript is that it allows the use of Interfaces, which we can use in this case to define a schema for our user model. So, under the models directory, we will create a file named UserModel.ts , with the content as:
export interface User { uid: string, email: string | undefined, displayName: string | undefined, lastSignInTime: string, creationTime: string, emailVerified: boolean, admin: boolean }
Before proceeding with creating the routes, we need to secure the endpoints to prevent unauthorized access. For this purpose, we will create and use two middlewares, one for Authentication and another one for Authorization, i.e, to ensure whether the user requesting the operation has sufficient privileges.
Let’s create two files, authenticate.middleware.ts , authorize.middleware.ts.
We will use authenticate to check if user has a valid idToken, and the authorize to check if the user has the required privileges.
Note: The authenticate filter requires an Authorization header with the value in the following form:- Bearer
Note: The idToken can be retrieved by signing-in to firebase using the REST API for firebase Authentication for the moment.
Proceeding further, we need to create a UsersController.ts file under modules →users that will contain the methods that our routes for “/users” path will utilize.
Here, “//RA” means the particular function requires admin privileges to perform its functionality.
This name of the methods define its functionality in this case.
getAllUsers() →Returns a list of all the users.
getUser() →Accepts an uid and returns the particular user.
updateUser() →Here we can perform many task, but in the current scope we will only set the displayName property of the user. You can play around with the function and find out all the fields that a user can have in firebase authentication.
createUser() →Creates an user.
createAdminUser() →Creates an user but with Admin privileges.
deleteUser() →Deletes the user whose uid is provided.
deleteUsers() →Deletes multiple users, uid array is fetched from body.
forceSignOut() →Forcibly revoke a users refresh token, so that their login can’t continue.
mapUserFromUserRecord() →An utility function, private to the file, which helps in extracting user from an UserRecord object returned by the admin sdk, returns a User _ object._
Here, we use customClaims to store the admin role for an user. These customClaims can only be retreived through the admin SDK. (I didn’t find any way to retrieve them from the client sdk, Kindly mention in the feedback if I am wrong.)
We need a router that can map different routes to the functions. For that purpose we create a file routes.ts in the same directory. The file contains the following.
Here, we define a configureRoutes function, which will take our express app and add the routes. We pass true to authorize where the route requires admin privilege to perform the task.
Similarly, we create two files, adminController.ts and routes.ts under modules →admin.
Finally, we add the following import statements to the index.ts _ _file.
import { configureRoutes as configureRoutesForUsers } from './modules/users/routes'; import { configureRoutes as configureRoutesForAdmin } from './modules/admin/routes';
We listen for the endpoints by starting the server using the following piece of code:
app.listen( port, () => { console.log('Server listening at port '+ port); });
Finally start the server on localhost using
npm start
We can use Postman to test the endpoints. Ex:.
We can add users to the project by using the firebase console or by using the REST API for firebase. And thereafter we can retrieve the uid from the firebase console.
Note: For the first time, to add an admin, we can normally add an user and call the /admin/:uid/make endpoint by passing false to its authorize filter. After that we can revert the value to true.
Kindly refer to the following Github repository for the complete project files.
i-am-jyotirmaya/Firebase-admin-demo-api
Discussion (0) | https://dev.to/iamdoctorj/a-simple-control-panel-for-application-admins-to-manage-users-and-privileges-using-firebase-3a43 | CC-MAIN-2021-10 | refinedweb | 1,519 | 58.69 |
from __future__ import print_function, division
There's a widespread trend in solar physics at the moment for correlation over actual science, so being able to handle data over time spans is a skill we all need to have. Python has ample support for this so lets have a look at what we can use.
SunPy provides a lightcurve object to handle this type of time series data. The module has a number of instruments associated with it, including:
We're going to examine the lightcurves created by a solar flare on June 7th 2011.
Lets begin with the import statements:
from __future__ import print_function, division import numpy as np import sunpy from sunpy import lightcurve as lc import matplotlib.pyplot as plt %matplotlib inline import warnings warnings.filterwarnings('ignore')
Now lets create some lightcurves
goes_lightcurve = lc.GOESLightCurve.create('2011-06-07 06:00','2011-06-07 08:00') hsi_lightcurve = lc.RHESSISummaryLightCurve.create('2011-06-07 06:00','2011-06-07 08:00')
In terms of LYRA, the server only allows you to download an entire day of data at a time. We can match this to the rest of the data by using the truncate function.
lyra_lightcurve_fullday = lc.LYRALightCurve.create('2011-06-07') lyra_lightcurve = lyra_lightcurve_fullday.truncate('2011-06-07 06:00','2011-06-07 08:00')
Part of the advantage of using these inbuilt functions we can get a quicklook at our data using short commands:
fig = goes_lightcurve.peek() fig = lyra_lightcurve.peek()
More custom plots can be made easily by accessing the data in the lightcurve functionality. Both the time information and the data are contained within the lightcurve.data code, which is a pandas dataframe. We can see what data is contained in the dataframe by finding which keys it contains and also asking what's in the meta data:
print(lyra_lightcurve.data.keys())
print(lyra_lightcurve.meta)
Notice that the meta data information is stored in something called
OrderedDict'])
We can use these keys to plot specific parameters from the lightcurve, Aluminium is 'CHANNEL_3' and Zirconium is 'CHANNEL_4. These measurements are taken on a instuments which detect events at different energy levels.)') plt.show()
cross_correlation = np.correlate(lyra_lightcurve.data['CHANNEL3'], lyra_lightcurve.data['CHANNEL4']) print(cross_correlation)
In its own words Pandas is a Python package providing fast, flexible, and expressive data structures designed to make working with “relational” or “labeled” data both easy and intuitive. Pandas has two forms of structures, 1D series and 2D dataframe. It also has its own functions associated with it.
It is also amazing.
Lightcurve uses these in built Pandas functions, so we can find out things like the maximum of curves:
# max time argument taken from long and short GOES channels max_t_goes_long = goes_lightcurve.data['xrsb'].idxmax() max_t_goes_short = goes_lightcurve.data['xrsa'].idxmax() # max_time argument taken from channel 3 & 4 LYRA channe;s max_t_lyra_al = lyra_lightcurve.data['CHANNEL3'].idxmax() max_t_lyra_zr = lyra_lightcurve.data['CHANNEL4'].idxmax() print('GOES long: ', max_t_goes_long) print('GOES short: ', max_t_goes_short) print('LYRA Al: ', max_t_lyra_al) print('LYRA Zr: ', max_t_lyra_zr)
So lets plot them on the graph
# create figure with raw curves)') # max lines plt.axvline(max_t_lyra_al,color='blue',linestyle='dashed', linewidth=2) plt.axvline(max_t_lyra_zr,color='red',linestyle='dashed') plt.axvline(max_t_goes_long,color='green',linestyle='dashed',linewidth=2)
data = np.genfromtxt('macrospicules.csv', skip_header=1, dtype=None, delimiter=',')
Now, the above line imports information on some solar features over a sample time period. Specifically we have, maximum length, lifetime and time at which they occured. Now if we type
data[0] what will happen?
data[0]
This is the first row of the array, containing the first element of our three properties. This particular example is a stuctured array, so the columns and rows can have properties and assign properties to the header. We can ask what the title of these columns is by using a
dtype command:
data.dtype.names
Unhelpful, so lets give them something more recognisable. We can use the docs to look up syntax and change the names of the column lables.
data.dtype.names = ('max_len', 'ltime', 'sample_time') data['max_len']
Now a pandas DataFrame takes two arguments as a minimum, index and data. In this case the index will be our time within the sample and the maximum length and lifetime will be our data. So lets import pandas and use the dataframe:
Pandas reads a dictionary when we want to input multiple data columns. Therefore we need to make a dictionary of our data and read that into a pandas data frame. First we need to import pandas.'])
First, let's import Pandas:
import pandas as pd d = {'max_len': data['max_len'], 'ltime': data['ltime']} df = pd.DataFrame(data=d, index=data['sample_time']) print(df)
Notice that the time for the sample is in a strange format. It is a string containing the date in YYYY-MM-DD and time in HH-MM-SS-mmmmmm. These datetime objects have their own set of methods associated with them. Python appreciates that theses are built this way and can use them for the indexing easily.
We can use this module to create date objects (representing just year, month, day). We can also get information about universal time, such as the time and date today.
NOTE: Datetime objects are NOT strings. They are objects which print out as strings.
import datetime print(datetime.datetime.now()) print(datetime.datetime.utcnow()) lunchtime = datetime.time(12,30) the_date = datetime.date(2005, 7, 14) dinner = datetime.datetime.combine(the_date, lunchtime) print("When is dinner? {}".format(dinner))
Looking back at when we discussed the first element of data, and the format of the time index was awkward to use so lets do something about that.
print(df.index[0])
This is a string and python will just treat it as such. We need to use datetime to pick this string appart and change it into an oject we can use.
So we use the formatting commands to match up with the string we have.
dt_obj = datetime.datetime.strptime(df.index[0], '%Y-%m-%dT%H:%M:%S.%f') print(dt_obj)
Now the next logical step would be to make a for loop and iterate over the index and reassign it. HOWEVER there is almost always a better way. And Pandas has a
to_dateime() method that we can feed the index:
df.index = pd.to_datetime(df.index) df
Much easier. Note that the format of table has now changed and are pandas specific datetime objects, and looks like this:
df.index[0]
This means we can bin data according to time
l_bins = pd.groupby(df['max_len'], by=[df.index.year, df.index.month]) print(len(l_bins))
Here we have used the groupby command to take the
'max_len' column, called as a dictionary key, and create bins for our data to sit in according to year and then month.
The object
l_bins has
mean,
max,
std etc. attributes in the same way as the numpy arrays we handled the other day.
l_mean = l_bins.mean() l_std = l_bins.std()
Lets not forget that
l_bins is a list of bins so when we print out
l_mean we get:
print(l_mean)
Now we have all this data we can build a lovely bargraph with error bars and wonderful things like that.
Remember, these pandas objects have functions associated with them, and one of them is a plot command.
fig, ax = plt.subplots() fig.autofmt_xdate() l_mean.plot(kind='bar', ax=ax, yerr=l_std, grid=False, legend=False) plt.show()
Note that the date on the x-axis is a little messed up we can fix with
fig.autofmt_xdate()
import numpy as np ep_data = np.loadtxt('data/XO1_wl_transit_FLUX.txt')
ep_dict = {'flux':ep_data[:, 1], 'err_flux':ep_data[:, 2]}
ep_df = pd.DataFrame(data=ep_dict, index=ep_data[:,0]) ep_df.index = pd.to_datetime(ep_df.index)
from astropy.time import Time t = Time(ep_data[:, 0], format='jd') UTC = t.datetime
ep_df.index = UTC
ep_df | https://nbviewer.jupyter.org/github/OpenAstronomy/2016-01-11_Sheffield_Notes/blob/master/08-Time-Series-Data_Instructor.ipynb | CC-MAIN-2019-13 | refinedweb | 1,300 | 58.08 |
Gearman::Client - Client for gearman distributed job system.
Creates a new Gearman::Client object, and returns the object.
If %options is provided, initializes the new client object with the settings in %options, which can contain:
Calls job_servers (see below) to initialize the list of job servers. Value in this case should be an arrayref.
Calls prefix (see below) to set the prefix / namespace..
Dispatches a task and doesn't wait for the result. Return value is an opaque scalar that can be used to refer to the task.
Creates and returns a new Gearman::Taskset object.
Adds a task to a taskset. Three different calling conventions are available.
Waits for a response from the job server for any of the tasks listed in the taskset. Will call the on_* handlers for each of the tasks that have been completed, updated, etc. Doesn't return until everything has finished running or failing.
Sets the namespace / prefix for the function names.
See Gearman::Worker for more details..
License granted to use/distribute under the same terms as Perl itself.
This is free software. This comes with no warranty whatsoever.
Brad Fitzpatrick (brad@danga.com) Jonathan Steinert (hachi@cpan.org) | http://search.cpan.org/~dormando/Gearman/lib/Gearman/Client.pm | CC-MAIN-2017-13 | refinedweb | 197 | 70.5 |
Bernhard Herzog" <bh at intevation.de> wrote in message news:6q4rrlsck9.fsf at abnoba.intevation.de... [ ... ] > > It seems to me that with nested scopes f should be able to access the > surrounding scope's names. > Indeed it should, but remember that these scopes are STATIC (i.e. determined at compile time) and not dynamic ("I'll just have a look in my caller's local namespace to see whether what I want is there"). Thus by the time you call f, the compiler has already determined which names are from nested scopes, by looking at functions whose definition surrounds the definition of f. If there aren't any, no nested scopes. regards STeve -- | https://mail.python.org/pipermail/python-list/2001-August/099001.html | CC-MAIN-2014-10 | refinedweb | 113 | 75.3 |
These examples assume you are using the WMI module from this site. The following are examples of useful things that could be done with this module on win32 machines. It hardly scratches the surface of WMI, but that’s probably as well.
The following examples, except where stated otherwise, all assume that you are connecting to the current machine. To connect to a remote machine, simply specify the remote machine name in the WMI constructor, and by the wonders of DCOM, all should be well:
import wmi c = wmi.WMI ("some_other_machine")
Note.))
Note
This is an example of running a process and knowing when it’s finished, not of manipulating text typed into Notepad. So I’m simply relying on the fact that I specify what file notepad should open and then examining the contents of that afterwards.
This one won’t work as shown on a remote machine because, for security reasons, processes started on a remote machine do not have an interface (ie you can’t see them on the desktop). The most likely use for this sort of technique on a remote server to run a setup.exe and then, say, reboot once it’s.Win32_PrintJob.watch_for ( notification_type="Creation", delay_secs=1 ) while 1: pj = print_job_watcher () print "User %s has submitted %d pages to printer %s" % \ (pj.Owner, pj.TotalPages, pj.Name)
Note.
Note
This example and the ones below use the convenience function Registry() which was added to the wmi package in its early days. It’s exactly equivalent to:
import wmi r = wmi.WMI (namespace="DEFAULT").StdRegProv] )
Note
This page at Microsoft is quite a good starting point for handling printer matters with WMI.
import wmi c = wmi.WMI () for printer in c.Win32_Printer (): print printer.Caption for job in c.Win32_PrintJob (DriverName=printer.DriverName): print " ", job.Document print
Note
Example is after a post by Roger Upole to the python-win32 mailing list
import wmi c = wmi.WMI () c.Win32_Product.Install ( PackageLocation="c:/temp/python-2.4.2.msi", AllUsers=False )
Note
You cannot connect to your own machine this way, no matter how hard you try to obfuscate the server" )
import wmi c = wmi.WMI () for opsys in c.Win32_OperatingSystem (): break print opsys.Reboot print opsys.Shutdown
Note
The WMI ScheduledJob class correponds to the AT Windows service (controlled through the “at” command). As far as I know, it is not related to the Scheduled Tasks mechanism, controlled by a control panel applet.
import os import wmi c = wmi.WMI () one_minutes_time = datetime.datetime.now () + datetime.timedelta (minutes=1) job_id, result = c.Win32_ScheduledJob.Create ( Command=r"cmd.exe /c dir /b c:\ > c:\\temp.txt", StartTime=wmi.from_time (one_minutes_time) ) print job_id for line in os.popen ("at"): print line
Note
Thanks to Keith Veleba for providing the question and code which prompted this example
import wmi SW_SHOWMINIMIZED = 1 c = wmi.WMI () startup = c.Win32_ProcessStartup.new (ShowWindow=SW_SHOWMINIMIZED) pid, result = c.Win32_Process.Create ( CommandLine="notepad.exe", ProcessStartupInformation=startup ) print pid
import wmi DRIVE_TYPES = { 0 : "Unknown", 1 : "No Root Directory", 2 : "Removable Disk", 3 : "Local Disk", 4 : "Network Drive", 5 : "Compact Disc", 6 : "RAM Disk" }
Note the use of pythoncom.Co(Un)initialize. WMI is a COM-based technology, so to use it in a thread, you must init the COM threading model. This applies also if you’re running in a service, for example, which is implicitly threaded.’t have to poll for them so you shouldn’t miss any. The multiple machines was just a practical example of using threads.
Note
Note the use of CoInitialize and CoUninitialize in the thread control code. Note also the simplified use of _wmi_class.watch_for() which will work for intrinsic and extrinsic events transparently.
import't't be named # after Harry Potter characters. And which hopefully # use a less obvious admin password. # servers = [ ("goyle", "administrator", "secret"), ("malfoy", "administrator", "secret") ] if __name__ == '__main__':Stretched, desktop.WallpaperTiled | http://timgolden.me.uk/python/wmi/cookbook.html | CC-MAIN-2015-35 | refinedweb | 646 | 58.99 |
Programming the camera
From OLPC
This page explores how to interact with the laptop's built-in video camera.
Getting started
First, let's see the quickest way we can capture a still image from the camera--using a GStreamer command-line tool:
gst-launch-0.10 v4l2src ! ffmpegcolorspace ! pngenc ! filesink location=foo.png
If you're typing that command in by hand, note that "v4l2src" begins with the characters vee-four-ell-two, an abbreviation for "Video 4 Linux 2.0", and not the number four hundred and twelve. You'll need to run the above command in a terminal, either the Terminal activity, in the developer console (alt-=) or one of the virtual terminals (e.g. ctrl-alt-f1). Note this means you don't need the Sugar GUI to be running to access the camera.
You can view the PNG image created as a result of the command in the Web activity.
Now, let's try and get some video on the screen:
gst-launch-0.10 v4l2src ! xvimagesink
Unlike the first command this command will only work with an X display, eg when executed in Terminal activity or a terminal in the developer console.
Since you've now had your first hit of "ooo, shiny" moving pictures let's take a look at what's happening behind the scenes.
What just happened?
I'm going to assume you have a passing familiarity with GStreamer, if not, you could go read about it. Basically, it's a series of pipes you can throw multimedia data down and get something in a file or on screen at the end. The data starts at a source (src) and ends up in a sink (sink) and can go through a number of intermediate manipulations along the way.
While we will get to using the camera from Python eventually, we've started out with using the GStreamer command line tool gst-launch. The gst-launch tool is a quick way to experiment with putting a pipeline together and seeing what it does.
Let's take a look at that first command line again:
gst-launch-0.10 v4l2src ! ffmpegcolorspace ! pngenc ! filesink location=foo.png
The camera in a XO laptop is a regular Video4Linux 2 device which is accessed via GStreamer's v4l2src source. Since the camera is our source it's the first item in our pipeline--notice the individual parts of the pipeline are separated with ! characters. (You could say the data goes out with a bang but it'd be a pretty bad joke.)
Next, we'll skip to look at the end of the pipeline--the sink end--here we find the filesink which simply outputs some data to a particular file. The name of the file (in our case foo.png) is provided by specifying location=foo.png—this is an example of how to supply arguments to the individual items in the pipeline. (Note: if you try to use name= it won't work! The name parameter is for referring to the element in the pipeline, not the name of the destination file.)
As you can probably guess, the pngenc plugin is in the pipeline to convert the data from the video camera into the PNG file format before it is written to the the file.
The only other item in the pipeline is the delightfully named ffmpegcolorspace plugin which performs colorspace conversions—essentially the v4l2src and pngenc plugins can't talk to each other directly because they each describe images in different ways, it's the job of ffmpegcolorspace to enable them to communicate by translating between the two styles of image description.
Doing it in Python
Implementing the same pipeline in Python might look like this:
import gst import tempfile GST_PIPE = ['v4l2src', 'ffmpegcolorspace', 'pngenc'] class Camera(object): """A class representing the OLPC camera.""" def __init__(self): snap_file, self.snap_path = tempfile.mkstemp() pipe = GST_PIPE + ['filesink location=%s' % self.snap_path] self.pipe = gst.parse_launch('!'.join(pipe)) self.bus = self.pipe.get_bus() def Snap(self): """Take a snapshot.""" self.pipe.set_state(gst.STATE_PLAYING) self.bus.poll(gst.MESSAGE_EOS, -1) if __name__ == '__main__': c = Camera() c.Snap() print c.snap_path
GStreamer 101
Moved to GStreamer#GStreamer 101.
See also
- Category:Camera
- Vision processing
-
- ALE is an image-processing program used for tasks such as image mosaicking, super-resolution, deblurring, noise reduction, anti-aliasing, and scene reconstruction. Its principle of operation is synthetic capture, combining multiple inputs representing the same scene.
- MotionDetection | http://wiki.laptop.org/go/Programming_the_camera | CC-MAIN-2017-43 | refinedweb | 744 | 53.31 |
FSM
Overview
The FSM (Finite State Machine) is available as a mixin for the akka Actor and is best described in the Erlang design principles akka.util.duration._
The contract of our “Buncher” actor is that is accepts or produces the following messages:
// received events case class SetTarget(ref: ActorRef) case class Queue(obj: Any) case object Flush // sent events case class Batch(obj:: Seq[Any]) extends Data
The actor can be in two states: no message queued (aka Idle) or some message queued (aka Active). It will stay in the active state as long as messages keep arriving and no flush is requested. The internal state data of the actor is made up of the target actor reference to send the batches to and the actual queue of messages.
Now let’s take a look at the skeleton for our FSM actor:
class Buncher extends Actor with FSM[State, Data] { startWith(Idle, Uninitialized) when(Idle) { case Event(SetTarget(ref), Uninitialized) ⇒ stay using Todo(ref, Vector.empty) } // transition elided ... when(Active, stateTimeout = 1 second) { case Event(Flush | FSM defines the initial state and initial data
- then there is one when(<state>) { ... } declaration per state to be handled (could potentially be multiple ones, the passed PartialFunction will be concatenated using orElse)
- finally starting it up using initialize, which performs the transition into the initial state and sets up timers (if required).
In this case, we start out in the Idle and Uninitialized state, where only the SetTarget() message is handled; stay prepares to end this event’s processing for not leaving the current state, while the using modifier makes the FSM replace the internal state (which is Uninitialized at this point) with a fresh Todo() object containing the target actor reference. The Active state has a state timeout declared, which means that if no message is received for 1 second, a FSM.StateTimeout message will be generated. This has the same effect as receiving the Flush command in this case, namely to transition back into the Idle state and resetting the internal queue to the empty vector. But how do messages get queued? Since this shall work identically in both states, we make use of the fact that any event which is not handled by the when() block is passed to the whenUnhandled() block:
whenUnhandled { // common code for both states case Event(Queue(obj), t @ Todo(_, v)) ⇒ goto(Active) using t.copy(queue = v :+ obj) case Event(e, s) ⇒ log.warning("received unhandled request {} in state {}/{}", e, stateName, s) stay }
The first case handled here is adding Queue() requests to the internal queue and going to the Active state (this does the obvious thing of staying in the Active state if already there), but only if the FSM data are not Uninitialized when the Queue() event is received. Otherwise—and in all other non-handled cases—the second case just logs a warning and does not change the internal state.
The only missing piece is where the Batches are actually sent to the target, for which we use the onTransition mechanism: you can declare multiple such blocks and all of them will be tried for matching behavior in case a state transition occurs (i.e. only when the state actually changes).
onTransition { (Scala), which is conveniently bundled with ScalaTest traits into AkkaSpec:
import akka.testkit.AkkaSpec import akka.actor.Props class FSMDocSpec extends AkkaSpec { "simple finite state machine" must { // fsm code elided ... "batch correctly" in { val buncher = system.actorOf(Props(new Buncher)) buncher ! SetTarget(testActor) buncher ! Queue(42) buncher ! Queue(43) expectMsg(Batch(Seq(42, 43))) buncher ! Queue(44) buncher ! Flush buncher ! Queue(45) expectMsg(Batch(Seq(44))) expectMsg(Batch(Seq(45))) } "batch not if uninitialized" in { val buncher = system.actorOf(Props(new Buncher)) buncher ! Queue(42) expectNoMsg } } }
Reference
The FSM Trait and Object
The FSM trait may only be mixed into an Actor. Instead of extending Actor, the self type approach was chosen in order to make it obvious that an actor is actually created. Importing all members of the FSM object is recommended if you want to directly access the symbols like StateTimeout. This import is usually placed inside the state machine definition:
class MyFSM extends Actor with FSM[State, Data] { import FSM._ ... }
The FSM trait takes two type parameters:
- the supertype of all state names, usually a sealed trait with case objects extending it,
- the type of the state data which are tracked by the FSM module itself.
Note
The state data together with the state name describe the internal state of the state machine; if you stick to this scheme and do not add mutable fields to the FSM class you have the advantage of making all changes of the internal state explicit in a few well-known places.
Defining States
A state is defined by one or more invocations of the method
when(<name>[, stateTimeout = <timeout>])(stateFunction).
The given name must be an object which is type-compatible with the first type parameter given to the FSM trait. This object is used as a hash key, so you must ensure that it properly implements equals and hashCode; in particular it must not be mutable. The easiest fit for these requirements are case objects.
If the stateTimeout parameter is given, then all transitions into this state, including staying, receive this timeout by default. Initiating the transition with an explicit timeout may be used to override this default, see Initiating Transitions for more information. The state timeout of any state may be changed during action processing with setStateTimeout(state, duration). This enables runtime configuration e.g. via external message.
The stateFunction argument is a PartialFunction[Event, State], which is conveniently given using the partial function literal syntax as demonstrated below:
when(Idle) { case Event(Start(msg), _) => goto(Timer) using (msg, sender) } when(Timer, stateTimeout = 12 seconds) { case Event(StateTimeout, (msg, sender)) => sender ! msg goto(Idle) }
The Event(msg: Any, data: D) case class is parameterized with the data type held by the FSM for convenient pattern matching.
Defining the Initial State
Each FSM needs a starting point, which is declared using
startWith(state, data[, timeout])
The optionally given timeout argument overrides any specification given for the desired initial state. If you want to cancel a default timeout, use Duration.Inf.
Unhandled Events
If a state doesn't handle a received event a warning is logged. If you want to do something else in this case you can specify that with whenUnhandled(stateFunction):
whenUnhandled { case Event(x : X, data) => log.info(this, "Received unhandled event: " + x) stay case Event(msg, _) => log.warn(this, "Received unknown event: " + x) goto(Error) }
IMPORTANT: This handler is not stacked, meaning that each invocation of whenUnhandled replaces the previously installed handler.
Initiating Transitions
The result of any stateFunction must be a definition of the next state unless terminating the FSM, which is described in Termination from Inside. The state definition can either be the current state, as described by the stay directive, or it is a different state as given by goto(state). The resulting object allows further qualification by way of the modifiers described in the following:
- forMax(duration)
This modifier sets a state timeout on the next state. This means that a timer is started which upon expiry sends a StateTimeout message to the FSM. This timer is canceled upon reception of any other message in the meantime; you can rely on the fact that the StateTimeout message will not be processed after an intervening message.
This modifier can also be used to override any default timeout which is specified for the target state. If you want to cancel the default timeout, use Duration.Inf.
- using(data)
- This modifier replaces the old state data with the new data given. If you follow the advice above, this is the only place where internal state data are ever modified.
- replying(msg)
- This modifier sends a reply to the currently processed message and otherwise does not modify the state transition.
All modifier can be chained to achieve a nice and concise description:
when(State) { case Event(msg, _) => goto(Processing) using (msg) forMax (5 seconds) replying (WillDo) }
The parentheses are not actually needed in all cases, but they visually distinguish between modifiers and their arguments and therefore make the code even more pleasant to read for foreigners.
Note
Please note that the return statement may not be used in when blocks or similar; this is a Scala restriction. Either refactor your code using if () ... else ... or move it into a method definition.
Monitoring Transitions
Transitions occur "between states" conceptually, which means after any actions you have put into the event handling block; this is obvious since the next state is only defined by the value returned by the event handling logic. You do not need to worry about the exact order with respect to setting the internal state variable, as everything within the FSM actor is running single-threaded anyway.
Internal Monitoring
Up to this point, the FSM DSL has been centered on states and events. The dual view is to describe it as a series of transitions. This is enabled by the method
onTransition(handler)
which associates actions with a transition instead of with a state and event. The handler is a partial function which takes a pair of states as input; no resulting state is needed as it is not possible to modify the transition in progress.
onTransition { case Idle -> Active => setTimer("timeout") case Active -> _ => cancelTimer("timeout") case x -> Idle => _) private def handler(from: State, to: State) { ... }
The handlers registered with this method are stacked, so you can intersperse onTransition blocks with when blocks as suits your design. It should be noted, however, that all handlers will be invoked for each transition, not only the first matching one. This is designed specifically so you can put all transition handling for a certain aspect into one place without having to worry about earlier declarations shadowing later ones; the actions are still executed in declaration order, though.
Note
This kind of internal monitoring may be used to structure your FSM according to transitions, so that for example the cancellation of a timer upon leaving a certain state cannot be forgot when adding new target states.
External Monitoring
External actors may be registered to be notified of state transitions by sending a message SubscribeTransitionCallBack(actorRef). The named actor will be sent a CurrentState(self, stateName) message immediately and will receive Transition(actorRef, oldState, newState) messages whenever a new state is reached. External monitors may be unregistered by sending UnsubscribeTransitionCallBack(actorRef) to the FSM actor.
Registering a not-running listener generates a warning and fails gracefully. Stopping a listener without unregistering will remove the listener from the subscription list upon the next transition.
Timers
Besides state timeouts, FSM manages timers identified by String names. You may set a timer using
setTimer(name, msg, interval, repeat)
where msg is the message object which will be sent after the duration interval has elapsed. If repeat is true, then the timer is scheduled at fixed rate given by the interval parameter. Timers may be canceled using
cancelTimer(name)
which is guaranteed to work immediately, meaning that the scheduled message will not be processed after this call even if the timer already fired and queued it. The status of any timer may be inquired with
timerActive_?(name)
These named timers complement state timeouts because they are not affected by intervening reception of other messages.
Termination from Inside
The FSM is stopped by specifying the result state as
stop([reason[, data]])
The reason must be one of Normal (which is the default), Shutdown or Failure(reason), and the second argument may be given to change the state data which is available during termination handling.
Note
It should be noted that stop does not abort the actions and stop the FSM immediately. The stop action must be returned from the event handler in the same way as a state transition (but note that the return statement may not be used within a when block).
when(A) { case Event(Stop, _) => doCleanup() stop() }
You can use onTermination(handler) to specify custom code that is executed when the FSM is stopped. The handler is a partial function which takes a StopEvent(reason, stateName, stateData) as argument:
onTermination { case StopEvent(Normal, s, d) => ... case StopEvent(Shutdown, _, _) => ... case StopEvent(Failure(cause), s, d) => ... }
As for the whenUnhandled case, this handler is not stacked, so each invocation of onTermination replaces the previously installed handler.
Termination from Outside
When an ActorRef associated to a FSM is stopped using the stop method, its postStop hook will be executed. The default implementation by the FSM trait is to execute the onTermination handler if that is prepared to handle a StopEvent(Shutdown, ...).
Warning
In case you override postStop and want to have your onTermination handler called, do not forget to call super.postStop.
Testing and Debugging Finite State Machines
During development and for trouble shooting FSMs need care just as any other actor. There are specialized tools available as described in Testing Finite State Machines and in the following.
Event Tracing
The setting akka.actor.debug.fsm in :ref:`configuration enables logging of an event trace by LoggingFSM instances:
class MyFSM extends Actor with LoggingFSM[X, Z] { ... }
This FSM will log at DEBUG level:
- all processed events, including StateTimeout and scheduled timer messages
- every setting and cancellation of named timers
- all state transitions
Life cycle changes and special messages can be logged as described for Actors.
Rolling Event Log
The LoggingFSM trait adds one more feature to the FSM: a rolling event log which may be used during debugging (for tracing how the FSM entered a certain failure state) or for other creative uses:
class MyFSM extends Actor with LoggingFSM[X, Z] { override def logDepth = 12 onTermination { case StopEvent(Failure(_), state, data) => log.warning(this, "Failure in state "+state+" with data "+data+"\n"+ "Events leading up to this point:\n\t"+getLog.mkString("\n\t")) } ... }
The logDepth defaults to zero, which turns off the event log.
Warning
The log buffer is allocated during actor creation, which is why the configuration is done using a virtual method call. If you want to override with a val, make sure that its initialization happens before the initializer of LoggingFSM runs, and do not change the value returned by logDepth after the buffer has been allocated.
The contents of the event log are available using method getLog, which returns an IndexedSeq[LogEntry] where the oldest entry is at index zero.
Examples
A bigger FSM example contrasted with Actor's become/unbecome can be found in the sources:
Contents | http://doc.akka.io/docs/akka/2.0.4/scala/fsm.html | CC-MAIN-2013-48 | refinedweb | 2,442 | 50.06 |
From: Miro Jurisic (macdev_at_[hidden])
Date: 2004-08-26 00:49:29
In article <08b601c48afa$eb621fb0$a901000a_at_mat>,
"Mathew Robertson" <mathew.robertson_at_[hidden]> wrote:
> So far during this thread, it may appear that I am saying dont bother...
> which is crap. It has been mentioned that there is no cross-platform GUI
> library. All I have tried to do is point out that there are other
> corss-platform libraries - and they are working hard at solving these vcry
> problems. Quite a few of them are open source, as such they tend to want to
> fix design flaws. The point being that they solved most of the problems
> discussed so far, yet they are still "not excellent" wrt. each point
> mentioned.
Every major C++ cross-platform library I am aware of has major issues wrt
backwards compatibility and legacy C++ code (e.g., poor STL integration, poor
user of namespaces, poor use of exceptions) even if you ignore the question of
how well its user experience fares on non-Windows platforms. I don't know how
hard they are working on it, but I have been waiting for years and I don't know
of a single one that's adequate yet -- most of them are not even good enough as
a starting point for what I would consider adequate.
Also, I don't think that sprinkling open source pixie dust on them magically
imbues them with special extraordinary ability or desire to fix design flaws :-)
meeroh
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/2004/08/70768.php | CC-MAIN-2021-43 | refinedweb | 267 | 71.95 |
Hi David, David Fang <address@hidden> writes: > /* The type of subrs, i.e., Scheme procedures implemented in C. Empty > function declarators are used internally for pointers to functions of > any arity. However, these are equivalent to `(void)' in C++, are > obsolescent as of C99, and trigger `strict-prototypes' GCC warnings > (bug #23681). */ (See <>.) > #ifdef BUILDING_LIBGUILE > typedef SCM (* scm_t_subr) (); > #else > typedef void *scm_t_subr; > #endif [...] > and after installation, BUILDING_LIBGUILE is no longer defined. Had > the typedef been kept as SCM (*scm_t_subr)(), then the C++ compiler > would have no reason to complain As explained above, it would complain because in C++ an empty declarator means that the function takes zero arguments, whereas in C it means that the function prototype is undefined—i.e., the function can take any number of arguments of any type. If you think the comment can be improved, please let me know. > cc1plus: warnings being treated as errors > ../../../src/guile/hackt-config.cc: In function 'void > HAC::guile_wrap::wrap_package_string_init()': > ../../../src/guile/hackt-config.cc:32: warning: ISO C++ forbids > casting between pointer-to-function and pointer-to-object In C++, instead of writing, say: --8<---------------cut here---------------start------------->8--- extern SCM bar (SCM x, SCM y); ... scm_c_define_gsubr ("foo", 1, 2, 3, &bar); --8<---------------cut here---------------end--------------->8--- you must write: --8<---------------cut here---------------start------------->8--- extern SCM bar (SCM x, SCM y); ... scm_c_define_gsubr ("foo", 1, 2, 3, (scm_t_subr) &bar); --8<---------------cut here---------------end--------------->8--- (Tested with G++ 4.5.1 -Wall.) If you use ‘guile-snarf’, it should do the right thing. Hope this helps, Ludo’. | http://lists.gnu.org/archive/html/guile-devel/2011-03/msg00004.html | CC-MAIN-2013-48 | refinedweb | 258 | 65.83 |
Opened 2 years ago
Closed 2 years ago
Last modified 2 years ago
#2086 closed enhancement (fixed)
Add C# binding using SWIG, and support for Xamarin.
Description
Support C# binding using SWIG. The resulting C# binding can then be used for C# apps, as well as for Xamarin projects.
Requirements:
- Install swig-csharp
- (For C#/Xamarin development): Download Visual Studio from xamarin.com.
How to create C# binding:
- Go to pjsip-apps/src/swig.
- Run make.
To create Xamarin sample app:
- From Visual Studio, create new solution "Forms". Name it pjsua2xamarin in directory pjsip-apps/src/swig/csharp (we will refer this directory as [csharp_dir]).
- In the multiplatform section (pjsua2xamarin.pjsua2xamarin):
- Add pjsua2 folder ([csharp_dir]/pjsua2xamarin/pjsua2xamarin/pjsua2).
- Add sample.cs file ([csharp_dir]/pjsua2xamarin/pjsua2xamarin/sample.cs).
- Add code to run sample (such as in pjsua2xamarin.Droid MainActivity.cs or pjsua2xamarin.iOS AppDelegate.cs):
pjsua2xamarin.sample test = new sample(); test.test1();
- Add PJSIP libraries.
- For Android: Add lib folder ([csharp_dir]/Droid/lib) and change the Build Action of libpjsua2.so to Android Native Library. For more details, please refer to the official doc.
- For iOS: Add the fat static library file (each architecture's resulting libpjsua2.a is located in [csharp_dir]/iOS/lib/[arch]). For more info, please refer to the official doc.
- Set application permissions.
See our sample apps (ipjsua for iOS and pjsua2 sample for Android) to see the typical basic permissions required.
Issues and solutions:
- The type or namespace name 'HandleRef' does not exist.
SWIG requires .NET 2 or later by default and uses HandleRef. Make sure you are using the supported .NET framework version.
- TypeInitializationException, dll not found, unable to find pjsua2.
This issue is likely caused by unsuccessful addition of the PJSIP libraries (see step 4 above), invalid path, or incorrect architecture of the libraries.
- Crashes when calling Endpoint.libInit(), or during initialization.
This is likely caused by unauthorized permission (see step 5 above). App must list the required permissions and in some cases, specifically request for the permissions to the user, and user must grant those permissions.
Change History (2)
comment:1 Changed 2 years ago by ming
- Resolution set to fixed
- Status changed from new to closed
comment:2 Changed 2 years ago by ming
Note: See TracTickets for help on using tickets.
In 5735: | https://trac.pjsip.org/repos/ticket/2086 | CC-MAIN-2020-05 | refinedweb | 382 | 52.36 |
> > I can accept that usually you are not interested in the stored
> > uid/gid. But doubt that you want to lose permission information when
> > you mount a tar file. Zip is a different kettle of fish since that
> > doesn't contain uid/gid/permissions.
>
> It's not about being not interested.
>
> It's because I'd want my programs, and other users, to have exactly
> the same access to the tgz contents through vfs as they have when
> accessing the tgz file directly.
OK, that makes sense, and it should be an option.
> Not some baroque combination of unobvious hard-coded permission
> rules, that aren't even visible through stat(), and which both
> increase permissions for the user and decrease it for others at the
> same time.
I look at it differently. I want the tar filesystem to be analogous
to running tar. When I run tar, other users are not notified of the
output, it's only for me. If they want to run tar, they can too.
The same can be true for tarfs. I mount it for my purpose, others can
mount it for theirs. Since the daemon providing the filesystem asways
runs with the same capabilities as the user who did the mount, I and
others will always get the permissions that we have on the actual tar
file.
The end result in permission rules is the _same_ as with your
proposal. There's nothing baroque in it.
Think of the "no permission for others" as "hiding", not as some
special permission rule. And if this hiding can be nicely done with
namespaces, all the better, I'll happily drop this feature at that
instant.
> I see why you may want to hide certain things from other users
> sometimes - the sshfs example is a good one. I daresay Al Viro could
> come up with a per-user or per-keyring mount point for those occasions :)
Yeah, maybe that's something worth exploring.
Thanks,
Miklos | http://article.gmane.org/gmane.linux.kernel/295707 | crawl-002 | refinedweb | 328 | 72.46 |
I am trying to implement an RNN-based model for time-series data and any help would be much appreciated! I have a reward signal I would like to utilize to backpropagate a loss through the RNN every n steps. I cannot seem to find a way to backpropagate anything without detaching the hidden state, but I don’t think that is a good approach in this case.
Let’s start from a simple example, straight from the PyTorch documentation, but amended such that one can step through the optimizer within the time loop:
import torch import torch.nn as nn rnn = nn.GRUCell(10, 20) optimizer = torch.optim.SGD(rnn.parameters(), lr=1e-3) input = torch.randn(6, 3, 10) hx = torch.randn(3, 20) output = [] for i in range(6): hx = rnn(input[i], hx) output.append(hx) hx.mean().backward(retain_graph=retain_graph) optimizer.step() optimizer.zero_grad()
In the above script, if
retain_graph is False, I get a “RuntimeError: Trying to backward through the graph a second time”. When
retain_graph is True, I get “RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation: [torch.FloatTensor [20, 60]]”.
I’ve seen some time-series RNN implementations online that don’t seem to bother with detaching the hidden state, so I suppose this used to work well in previous PyTorch versions. | https://discuss.pytorch.org/t/how-to-backpropagate-a-loss-through-time-series-rnn/151327 | CC-MAIN-2022-21 | refinedweb | 228 | 56.15 |
Removing the AWT toolkit from the java.awt namespace
Hi Everyone
I have just done a series of commits which were all a part of my attempt
to remove the AWT toolkit from the java.awt namespace.
Essentially all the files were moved from java.awt package to
org.jdesktop.lg3d.awt package
Also the files in org.jdesktop.lg3d.displayserver.awtpeer were moved to
org.jdesktop.lg3d.awtpeer
The AWT toolkit was using some of the protected/package access
methods/fields in java.awt and these are now accessed using reflection.
Down the line I am guessing that this will cause security problems when
we get our webstart working again. I have wrapped these
protected/package accesses in doPriveleged blocks but I havent done any
testing of that path yet. We will possibly address it when we get
webstart working again.
I have only tested this on Linux (java5 and java6) and havent done any
windows/solaris testing. Please let me know if I have broken anything...
Thanks
-krishna
---------------------------------------------------------------------
To unsubscribe, e-mail: interest-unsubscribe@lg3d.dev.java.net
For additional commands, e-mail: interest-help@lg3d.dev.java.net | https://www.java.net/node/657290 | CC-MAIN-2014-15 | refinedweb | 191 | 60.61 |
JustLinux Forums
>
Community Help: Check the Help Files, then come here to ask!
>
Programming/Scripts
> a couple questions about c
PDA
Click to See Complete Forum and Search -->
:
a couple questions about c
3m00
01-21-2003, 11:19 PM
K, here they go.
1. Whats the difference between void'ing and int'ing subroutines? (or, can you call subroutines in another way?)
2. Can I pass argc and argv variables to subroutines? (if not, how can I pass strings or serv_addr's to them?)
3. If I have a common .h file, what should they have that my other files don't? (special header files? stdio.h?)
truls
01-22-2003, 10:12 AM
1. Not exactly sure what your question is here. Are you talking about the return value of subroutines ( or "functions" are we geeks like to call them :p )?
2. Yes.
Your function would have to have the same signature as main, but you can easily pass them on.
void myFunction( int number, char **array)
{
int i;
for( i=0 ; i<number ; i++ ) {
printf( "line %d = %s\n", number, array[i] );
}
}
int main( int argc, char **argv )
{
myFunction( argc, argv );
return 0;
}
3. I'd avoid this. It's informative to see the individual headers each file uses. Also, if you have divided your classes/sourcefiles into logical entities the number of common include headers won't be all that large.
3m00
01-22-2003, 10:33 PM
Okie then, but can I void subroutines with argc and argv? Sorta like:
#include <Stdio.h>
void cool_function(int argc, char * argv[]){
printf("yahey - you gave %d arguments!\n",argc);}
int main(){
cool_function(yahey sup cool function);
}
Will it function like the real argc and argv?
truls
01-23-2003, 10:06 AM?
3m00
01-23-2003, 08:33 PM
Originally posted by truls?
Yeah, thats what I mean. (Because you "int main" so I thought you could "void a function".... ) Anyways, thanks. I didn't really think I could... but if so... it would have been sooo cool... :) \me hopes I can pass structs to functions...
Spawn913
01-23-2003, 09:52 PM
you can always pass struct pointers to functions.
that way you can still use the struct.
justlinux.com | http://justlinux.com/forum/archive/index.php/t-86009.html | crawl-003 | refinedweb | 374 | 85.89 |
An MVC View widget for tabular data. More...
#include <Wt/WTableView>
An MVC View widget for tabular data.
The view displays data from a WAbstractItemModel in a table. It provides incremental rendering, provides virtual scrolling in both horizontal and vertical directions, and can therefore be used to display large data models (with large number of columns and rows).
When the view is updated, it will read the data from the model row per row, starting at the top visible row. If
(r1,c1) and
(r2,c2) are two model indexes of visible table cells, and
r1
<
r2 or
r1
==
r2 and
c1
<
c2, then the data for the first model index is read before the second. Keep this into account when implementing a custom WAbstractItemModel if you want to optimize performance. columns are given a width of 150px. Column widths of all columns can be set through the API method setColumnWidth(), and also by the user using handles provided in the header. view may receive a drop event on a particular item, at least if the item indicates support for drops (controlled by the ItemIsDropEnabled flag).
You may also react to mouse click events on any item, by connecting to one of the clicked() or doubleClicked() signals.
If a WTableView is not constrained in height (either by a layout manager or by setHeight()), then it will grow according to the size of the model.
Called when rows or columns are inserted/removed.
Override this method when you want to adjust the table's size when columns or rows are inserted or removed. The method is also called when the model is reset. The default implementation does nothing. model index corresponding to a widget.
This returns the model index for the item that is or contains the given widget..
Retrieves the preloading margin..
Signal emitted when scrolling.
Implements Wt::WAbstractItemView.
Sets if alternating row colors are to be used.
Configure whether rows get alternating background colors, defined by the current CSS theme.
The default value is
false.
Reimplemented from Wt::WAbstractItemView.
Changes the visibility of a column.
Reimplemented from Wt::WAbstractItemView.
Sets the column width.
The default column width is 150 pixels..
Sets the header height.
The default value is 20 pixels.
Reimplemented from Wt::WAbstractItemView. preloading margin.
By default the table view loads in an area equal to 3 times its height and 3 times its width. This makes it so that the user can scroll a full page in each direction without the delay caused when the table view dynamically needs to load more data.
setPreloadMargin() allows to customize this margin.
e.g. if the table view is H pixels high, and C is the preload margin in pixels set on the top and bottom, then enough rows are loaded to fill the area that is H + 2C pixels high. H pixels visible, C pixels above, and C pixels below.
Set to 0 pixels if you don't want to load more rows or columns than are currently visible.
Set to a default-constructed WLength (auto) if you want to keep default behaviour.. | https://webtoolkit.eu/wt/wt3/doc/reference/html/classWt_1_1WTableView.html | CC-MAIN-2021-31 | refinedweb | 514 | 66.54 |
do-while loop
Executes a statement repeatedly, until the value of expression becomes false. The test takes place after each iteration.
[edit] Syntax
[edit] Explanation
statement is always executed at least once, even if expression always yields false. If it should not execute in this case, a while or for loop may be used.
If the execution of the loop needs to be terminated at some point, a break statement can be used as terminating statement.
If the execution of the loop needs to be continued at the end of the loop body, a continue statement can be used as shortcut.
.
[edit] Keywords
[edit] Example
#include <iostream> #include <algorithm> #include <string> int main() { int j = 2; do { // compound statement is the loop body j += 2; std::cout << j << " "; } while (j < 9); std::cout << '\n'; // common situation where do-while loop is used std::string s = "aba"; std::sort(s.begin(), s.end()); do std::cout << s << '\n'; // expression statement is the loop body while(std::next_permutation(s.begin(), s.end())); }
Output:
4 6 8 10 aab aba baa | https://en.cppreference.com/w/cpp/language/do | CC-MAIN-2021-43 | refinedweb | 178 | 61.56 |
Paul Rubin wrote: > Christian Tismer <tismer at tismer.com> writes: > >>This leads to high-level descriptions of low-level >>fields of all structures. [...] > Do you have some other examples that really get used often? I'd think > f_lineno's don't get used that often. This was just an example for a common field (in fact it is used quite often at runtime, but almost only in the SET_LINENO opcode), that is embedded into some other structure. Everything else would to. The idea is to describe fixed data structures in a way that allows Python to easily deduce what the data type is, without any trial. See for example Thomas Heller's ctypes module, which has such descriptions for everything. A drawback of this is that we always need to access target variables in dotted notation. Otherwise we loose the static type info. If Python had type declarations, this would be no problem. Here an example from intobject.c: static int int_compare(PyIntObject *v, PyIntObject *w) { register long i = v->ob_ival; register long j = w->ob_ival; return (i < j) ? -1 : (i > j) ? 1 : 0; } Assuming that we try to model this in Python, the resulting code might look like this def int_compare(v, w): i, j = v.ob_ival, w.ob_ival if i < j: return -1 elif i > j: return 1 return 0 The above code only occours in contexts where integer objects are passed in. There is no type info in advance, but at the first execution of this code, v and w are passed in with their descriptions of all fields, and it is now absolutely clear that i and j are values of fixed sized integers. Code for directly accessing the ob_ival fields and doing the comparison can immediately be emitted when running the code first time. A remaining problem with the lack of declarations are local variables which are not members of a structure and it is not clear from the beginning what the primitive type should be. One ugly way would be to construct a structure for the local variables and to use dotted notation again. I hope this can be avoided by propagation of type info via __coerce__. Another snipped from intobject: for (i = 0, p = &list->objects[0]; i < N_INTOBJECTS; i++, p++) { if (PyInt_CheckExact(p) && p->ob_refcnt != 0) irem++; } Given a type object named c_int, this might translate to i = c_integer(0) p = list.objects while i < N_INTOBJECTS: # body not implemented here i += 1 p += 1 Here I use a known class as initialization of i. The data type is therefore known. p as a pointer field in the list structure is also known. The __coerce__ method of these classes can be written in a way, that they always propagate their own class to other operands, and especially in this case, the right operand is a constant. Given a definition like this: class c_integer(c_datatypes): def __coerce__(self, other): if type(other) == int: return self, c_integer(other) elif .... What I tried to express is that with little or no help of the programmer, primitive data types can be deduced quite easily, and unique code can be emitted on first execution of the code. >? | https://mail.python.org/pipermail/pypy-dev/2003-January/000121.html | CC-MAIN-2014-10 | refinedweb | 529 | 62.27 |
I am currently using firebase hosting for my single page React application. I have also added a 404.html page to my public directory. My assumption was that this page would get served if a user enter an url that is not in my routes(using react-router), but there is no way for firebase to know if an url is valid or not, or is there. Currently if I enter something random after the / of my main app url the page just shows blank. Is this something i need to account for within my React app, if so HOW?
You can let the React Router take care of serving a 404 page on the client side. This is how you can setup:
var NotFound = React.createClass({ render: function() { return (<h1>Page Not Found</h1>); } }); var App = React.createClass({ render: function() { <Router history={browserHistory}> <Route path="/" component={App}> <Route path="first" component={SomeComponent}/> <Route path="second" component={SomeOtherComponent}/> <Route path="*" component={NotFound}/> </Route> </Router> } });
Note that the catch all route (*) should be the last so that React Router can try all others and finally get to this.
Here's a nice article that explains this. | https://codedump.io/share/C9wnYxTgaw4C/1/how-do-i-serve-a-404-page-using-firebase-hosting-for-a-react-spa | CC-MAIN-2018-13 | refinedweb | 195 | 63.29 |
Date: May 13, 2010
Eclipse Labs is a community of open source projects that build technology based on the Eclipse platform. It provides the infrastructure services typically required by open source projects, such as code repositories, bug tracking, project web sites/wiki. Eclipse Labs is hosted by Google Code Project Hosting, so it will be very familiar to developers already using Google Code Project Hosting.
Please contact the normal Google Code Project Hosting support channels. Help is available at code.google.com/p/support/
All projects hosted on Eclipse Labs agreed to the standard Google Code Project Hosting terms of use and the Eclipse Labs User Guidelines.
No, Eclipse Labs projects are not official Eclipse Foundation projects. Eclipse Labs projects are not hosted by the Eclipse Foundation and do not have to follow the Eclipse Foundation development and intellectual property policies.
There are a number of things Eclipse Labs projects can not do since they are not official Eclipse Foundation projects, including 1) include the word Eclipse in their name, 2) use the org.eclipse namespace for their bundles names, or 3) participate in the annual Eclipse release trains, unless they are included in an official Eclipse project.
There are a number of benefits and obligations for hosting a project at the Eclipse Foundation. The benefits for your project include:
The obligations for being an Eclipse Foundation project may increase the effort and decrease the flexibility of starting an open source project. Eclipse Labs has been established for projects that don't want to come under the process and rules of the Eclipse Foundation but still want to be part of the greater Eclipse community. We would recommend projects starting on Eclipse Labs if one or more of the factors pretain to your project:
Yes. In fact we hope some projects will start at Eclipse Labs, build a community and technology, then eventually migrate to the Eclipse Foundation. If you believe at one time you will want to move your project to the Eclipse Foundation we suggest you ensure that 1) you keep track of all contributions and ensure they are contributed under the EPL. 2) do not include or link to any code that is licensed under the GPL. Unfortunately, that license is incompatible with the EPL. You should also be aware that there are important restrictions on the use and distribution of LGPL code by Eclipse projects.
If you have an existing project on Google Code that you would like to migrate to Eclipse Labs, file an issue here. Once an issue is filed, you will be contacted within the next 48 hours with instructions for how to migrate your project.
We are asking all projects on Eclipse Labs to identify the location of their P2 repository , so in the future it will be possible to create a composite repository for all Eclispe Labs projects. To identify the location of your P2 repo, go to the Admin tab and click on the 'Project Summary' sub-tab in your project. In the 'Project Summary' sub-tab, add a Link under the Link heading. Set the Link text to 'p2repo' and the link url to the url for the p2 repository . Save your changes.
Projects hosted at Eclipse Labs are expected to be Eclipse plugins or built with Eclipse technology. Therefore, the open source license you choose must be compatible with the Eclipse Public Licenese (EPL). These licenses are the compatible licenses available at Google Code Project Hosting.
Back to the top | https://www.eclipse.org/org/foundation/eclipselabs/faq.php | CC-MAIN-2020-34 | refinedweb | 582 | 69.01 |
A GameBench API Client Library.
Project description
A Python Client for the GameBench API
Please check out our ZenHub Board for open issues and feature requests.
For full documentation, go to the ReadtheDocs page.
Overview
To install, run
pip install GameBenchAPI-PyClient-BigFish
The GameBench API Client library supplies a high-level object-oriented interface to the GameBench API. It is built in Python 3.7 and uses the Requests library and Pandas data frames to easily integrate into data analysis software.
The library has two main architectural components; the models and API packages. The API package is responsible for URL requests and dealing with the responses. The models are the objects representing the data returned. A mediator provides the glue between the api and the models.
As a user of the library, you should only ever need to interact with the models creator class and the model objects it can return.
Right now, the models are very thin. They only contain a property that has the data frame assigned. Over time we would like to add common functionality, like aggregates, to these classes.
The Basics
To make a request, import the ModelCreator class. Instantiating the ModelCreator requires two arguments. The first is a CamelCase style 'model' named after the metric that you are looking for; the model is dynamically imported based on this name. The second argument is a dictionary that must include specific key/value pairs for querying the GameBench API.
from gamebench_api_client.models.creator.model_creator import ModelCreator time_series_request = { 'session_id': '66d926f47ff5a7a5d853d1058c6305614e1ae6a5' } creator = ModelCreator('Cpu', time_series_request) cpu_time_series = creator.get_model() results = cpu_time_series.data print(results) """ appUsage daemonUsage gbUsage timestamp totalCpuUsage 0 1372571.375 0 12.658228 5257 39.688461 """
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/GameBenchAPI-PyClient-BigFish/ | CC-MAIN-2020-05 | refinedweb | 306 | 51.24 |
- General settings
- Operations settings
Project settings
You can adjust your project settings by navigating to your project’s homepage and clicking Settings.
General settings
Under a project’s general settings you can find everything concerning the functionality of a project.
General project settings
Adjust your project’s name, description, avatar, default branch, and tags:
The project description also partially supports standard markdown. You can use emphasis, links, and line-breaks to add more context to the project description.
Sharing and permissions
Set up your project’s access, visibility, and enable Container Registry for your projects:
Issue settings
Add an issue description template to your project, so that every new issue will start with a custom template.
Merge request settings
Set up your project’s merge request settings:
- Set up the merge request method (merge commit, fast-forward merge).
- Merge request description templates.
- Enable merge request approvals.
- Enable merge only of pipeline succeeds.
- Enable merge only when all discussions are resolved.
Service Desk
Enable Service Desk for your project to offer customer support.
Export project
Learn how to export a project in GitLab.
Advanced settings
Here you can run housekeeping, archive, rename, transfer, or remove a project.
Archiving namespace
You can transfer an existing project into a group if:
- you have at least Maintainer permissions to that group
- you are an Owner of the project..
Operations settings
Jaeger tracing
Add the URL of a Jaeger server to allow your users to easily access the Jaeger UI from within Git | https://docs.gitlab.com/ee/user/project/settings/index.html | CC-MAIN-2018-51 | refinedweb | 248 | 55.13 |
We find the data are "messy" i.e aren't cleanly prepared for import - for instance numeric columns might have some strings in them. This is very common in raw data especially that obtained from web sites.
Let's take a look. we're going to look at the first five rows of some specific columns that show the data dirtiness issues.
loansData['Interest.Rate'][0:5] # first five rows of Interest.Rate
81174 8.90% 99592 12.12% 80059 21.98% 15825 9.99% 33182 11.71% Name: Interest.Rate, dtype: object
loansData['Loan.Length'][0:5] # first five rows of Loan.Length
81174 36 months 99592 36 months 80059 60 months 15825 36 months 33182 36 months Name: Loan.Length, dtype: object
We see here that:
Other than that we can also see (exploration exercise):
loansData['FICO.Range'][0:5] # first five rows of FICO.Range
81174 735-739 99592 715-719 80059 690-694 15825 695-699 33182 695-699 Name: FICO.Range, dtype: object
import matplotlib.pyplot as plt import pandas as pd plt.figure() loansmin = pd.read_csv('../datasets/loanf.csv') fico = loansmin['FICO.Score'] p = fico.hist()
import matplotlib.pyplot as plt import pandas as pd plt.figure() loansmin = pd.read_csv('../datasets/loanf.csv') p = loansmin.boxplot('Interest.Rate','FICO.Score') q = p.set_xticklabels(['640','','','','660','','','','680','','','','700', '720','','','','740','','','','760','','','','780','','','','800','','','','820','','','','840']) q0 = p.set_xlabel('FICO Score') q1 = p.set_ylabel('Interest Rate %') q2 = p.set_title(' ')
We're going to look at a scatterplot matrix of the five variables in our data.
## TRY THIS! import pandas as pd loansmin = pd.read_csv('../datasets/loanf.csv') a = pd.scatter_matrix(loansmin,alpha=0.05,figsize=(10,10), diagonal='hist') ## Click on the line above ## Change 'hist' to 'kde' then hit shift-enter, with the cursor still in this box ## The plot will redraw - it takes a while. While it is recomputing you will see a ## message-box that says 'Kernel Busy' near the top right corner ## You can change the code and hit shift-enter to re-execute the code ## Try changing the (10,10) to (8,8) and (12,12) ## Try changing the alpha value from 0.05 to 0.5 ## How does this change in alpha change your ability to interpret the data? ## Feel free to try other variations. ## If at any time you scramble the code and forget the syntax ## a copy of the original code is below. Copy and paste it in place. ## Remember to remove the hashmarks. ## a = pd.scatter_matrix(loansmin, alpha=0.05,figsize=(10,10), diagonal='hist)
from IPython.core.display import HTML def css_styling(): styles = open("../styles/custom.css", "r").read() return HTML(styles) css_styling() | http://nbviewer.jupyter.org/github/nborwankar/LearnDataScience/blob/master/notebooks/WA2.%20Linear%20Regression%20-%20Data%20Exploration%20-%20Lending%20Club%20Worksheet.ipynb | CC-MAIN-2018-26 | refinedweb | 447 | 63.76 |
Back in the seventies, I was taking entry exams to the Kiev Politechnic Institute (KPI). I lived in Ukraine, which was a part of the Soviet Union. At that time people of the Jewish descent had really hard time in getting into most of the colleges and universities. Typically, there were four entry exams for the engineering majors: the verbal math, the written math, the verbal physics, and essay. There were no such things as multiple choice tests ndash; we had to solve problems.
Being a Jewish boy myself, I was raised knowing that getting into college will four hundred people that were taking this test had to solve it. I caught the trick in that problem, and my written math grade was 4 out of 5. Two hundred and twenty people got 2 out of 5, which meant that they wouldn’t even problems were easy for me. I quickly wrote the answers, then helped to a girl sitting next to me (this was her 5th attempt to get admitted) and wrote all the answers to the guy in the military costume – guys who server 6 out of (failed). ” This meant the end of my exams. No i understand, that I should have selected each word more carefully, but getting 2 after seeing how people who know nothing are fetting 4? Ukraine.
So what does all this have with Java and job interviews here in the USA? These days I often interview people who apply for jobs. A face to face interview is similar to that entrance verbal exam. The only difference is that in the USA people are graded based on their skills rather than ethnicity.
But let’s imagine for a moment that you are conducting a technical interview on Java programming and need to have a special question to ensure that the person you don’t like won’t pass. I ‘m way of creating a Java thread ndash; subclass a Thread or implement Runnable. You also thought so? I know. The “new way rdquo; ‘s thinking about the best way of answering this easy question, then he writes the following on a piece of paper:
– If a method declared final, this method can’t be overridden.
static final double convertToCelsius(double far){
return ((far – 32) * 5 / 9);
}
– If a class is declared final, you can “t be subclass (extend) it
final class Tax { …};
– The value for the final variable can be assigned only once
static final int BOILING_TEMP = 212; // in Fahrenheit
Say politely, “Great, this is correct. Are these all uses of the keyword final that you can recollect? ” As I said earlier, the chances that the candidate knows the fourth use are about 5%. He goes, “Java has no any other use of the final keyword, I ‘m positive.” At this point you thank him for giving you great answers and say that an HR person will be in touch shortly. This is one of the major differences between the USA and USSR. We don’t say give the final answers while the candidate is still here. The phrase “Your answer is wrong ” or “You have a serious gap in trigonometry” could lead to unpredictable reaction of the candidate. We don’t want any conflicts. Let him leave in peace.
The mission is accomplished – he failed the job interview!
Recently released Java 7 has a new feature called final rethrow. In my opinion, it’s a pretty useless feature eliminating while interviewing candidates. So why did I write this blog? To be honest with you, I don’t know. For some reason, when I learned about this feature, I couldn’t find any other use for it other than a secret weapon for the dirty interviewers.
Update. After re-reading this blog, I realized that it didn’t cover an important use case: what if the job applicant knows about this fourth use of the final? Ask what he thinks about this new feature. If he has any opinion about this feature, hire him. He follows the latest developments in the Java language and cares to form an opinion. | https://yakovfain.com/2011/08/31/java-soviet-union-and-job-interviews/ | CC-MAIN-2018-05 | refinedweb | 685 | 70.94 |
Thanks for the helpfull information and support only problem is, after using the which command I get:
/usr/bin/aircrack-ng
so I gues this is also not right...? aircrack-ng commend is working tough
Printable View
Thanks for the helpfull information and support only problem is, after using the which command I get:
/usr/bin/aircrack-ng
so I gues this is also not right...? aircrack-ng commend is working tough
Would it be safe to assume that running this script could upgrade my installation to R1? I realize that R1 also has additional tools that might not be upgraded with this script, but would the end result be about the same if I don't need those additional tools?
For users of BT5r1, update line 104 to the below so you can update metasploit (it fails without this change as the framework3 directory doesn't exist anymore). Awesome script by the way, thanks for your work!
if subprocess.Popen("cd /pentest/exploits/framework/ && svn up",shell=True).wait() == 0:
many thanks for your jobs :cool:
Update for script coming in a few days depending on my free time, for those who don't want to get messy and follow arclight's suggestion wait a few days :)
@nivong: that is precisely what it should report. again, show us something to duplicate your "problem". and a seperate thread may be a good idea as you are polluting this thread with side issues unrelated to the script this thread is about.
root@bt:~# cd /pentest/wireless/aircrack-ng/
root@bt:/pentest/wireless/aircrack-ng# dir
post the output. in a *different thread*. we have established this has nothing to do with sickness' update bt5 script.
does this script eliminates the command (#~: apt-get upgrade / update) ?
just wanted to be sure before I run the script and won't run to any error because of the script.
It doesn't eliminate the commands, it leverages them:Running that particular function will take you from BT5 to BT5R1Running that particular function will take you from BT5 to BT5R1Code:
def backtrack_update():
print " [>] Updating and cleaning Backtrack, please wait.\n"
if subprocess.Popen("apt-get update && apt-get -y dist-upgrade && apt-get autoremove -y && apt-get -y autoclean",shell=True).wait() == 0:
print "\n"
print " [>] Backtrack updated and cleaned successfully!\n"
else:
print "\n"
print " [>] Failed to update Backtrack.\n" | http://www.backtrack-linux.org/forums/printthread.php?t=41766&pp=10&page=13 | CC-MAIN-2015-18 | refinedweb | 396 | 62.07 |
Integrative Case 4.doc Download Attachment
Integrative Case 4: O’Grady Apparel Company O’Grady Apparel Company was founded nearly 160 years
ago when an Irish merchant named Garrett O’Grady landed in Los Angeles with an inventory of...Integrative Case 4: O on the over- the-counter exchange. In 2006,
the Los Angeles– based company experienced sharp increases in both domestic and European markets
resulting in record earnings. Sales rose from $ 15.9 million in 2005 to $ 18.3 million in 2006 with earnings
per share of $ 3.28 and $ 3.84, respectively. European sales represented 29% of total sales in 2006, up
from 24% the year before and only 3% in 2001, 1 year after foreign operations were launched. Although
foreign sales represent nearly one- third of total sales, the growth in the domestic market is expected to
affect the company most markedly. Management expects sales to surpass $ 21 million in 2007, and
earnings per share are expected to rise to $ 4.40. ( Selected income statement items are presented in
Table 1.)
Table 1. Selected Income Statement Items
2004 2005 2006 Projected 2007
Net sales $ 13,860,000 $ 15,940,000 $ 18,330,000 $ 21,080,000
Net profits after taxes 1,520,000 1,750,000 2,020,000 2,323,000
Earnings per share ( EPS) 2.88 3.28 3.84 4.40
Dividends per share 1.15 1.31 1.54 1.76
Because of the recent growth, Margaret Jennings, the corporate treasurer, is concerned that available
funds are not being used to their fullest potential. The projected $ 1,300,000 of internally generated 2007. The
investment opportunities schedule ( IOS).
Investment Opportunities Schedule ( IOS)
Investment opportunity Internal rate of return ( IRR) Initial investment
A 21% $ 400,000
B 19 200,000
C 24 700,000
D 27 500,000
E 18 300,000
F 22 600,000
G 17 500,000
Financing Cost Data Long- term debt: The firm can raise $ 700,000 of additional debt by selling 10- year,
$ 1,000, 12% annual interest rate bonds to net $ 970 after flotation costs. Any debt in excess of $ 700,000
will have a before- tax cost, kd, of 18%.
Preferred stock: Preferred stock, regardless of the amount sold, can be issued with a $ 60 par value and
a 17% annual dividend rate. It will net $ 57 per share after flotation costs.
Common stock equity: The firm expects its dividends and earnings to continue to grow at a constant rate
of 15% per year. The firm’s stock is currently selling for $ 20 per share. The firm expects to have $
1,300,000 of available retained earnings. Once the retained earnings has been exhausted, the firm can
raise additional funds by selling new common stock, netting $ 16 per share after under- pricing and
flotation costs.
1. Over the relevant ranges noted in the following table, calculate the after- tax cost of each source of
financing needed to complete the table.
Source of capital Range of new financing After- tax cost (%)
Long- term debt $ 0–$ 700,000 ___
$ 700,000 and above ___
Preferred stock $ 0 and above ___
Common stock equity $ 0–$ 1,300,000 ___
$ 1,300,000 and above ___
2. a. Determine the break points associated with each source of capital. b. Using the break points
developed in part ( 1), determine each of the ranges of total new financing over which the firm’s weighted
average cost of capital ( WACC) remains constant. c. Calculate the weighted average cost of capital for
each range of total new financing.
3. a. Using your findings in part b( 3) with the investment opportunities schedule ( IOS), draw the firm’s
weighted marginal cost of capital ( WMCC) schedule and the IOS on the same set of axes, with total new
financing or investment on the x axis and weighted average cost of capital and IRR on the y axis. b.
Which, if any, of the available investments would you recommend that the firm accept? Explain your
answer.
4..)
b. Which capital structure— the original one or this one— seems better? Why?
5. a. What type of dividend policy does the firm appear to employ? Does it seem appropriate given the
firm’s recent growth in sales and profits and given its current investment opportunities? b. Would you
recommend an alternative dividend policy? Explain. How would this policy affect the investments
recommended in part c( 2)?
View Full Attachment Show more
Related Questions
FIN 605 Case Study 4Please review the following case and use it as the basis for your analysis for this unit. Pay careful attention to the situation and note the specific events as they might apply to the information from your chapter. You will use this data to form the basis of your analysis....
Please give me an advise on how to show the case study
I need help on these 3 questions6. Review current studies and literature and tell me what percent increases/decreases we can expect commercial rates, medicare rates, and medicaid rates to be over the next three years. What impact will those rate increases/decreases have on our operations?7....
This is a HBS case study about Equity Security Analysis. HBS CASE Name : DICOM Group plc and Captiva Software Corp.Required: 3 Pages (12 font size, 1.5 Spacing ) with accompanying table and figures. the report should contain a discussion of the issues, your recommendations, and analysis,...
Babes N Toyland Case Study
Case Study: Apple CorporationDownload the last 5 years of financial statements and put them into your report.Complete a 5 yr. set of pro forma financial statements, going forward.Answer the following questions:1. How is Apple positioned in its industry for growth?5. What is Apple 's dividend... | http://www.coursehero.com/tutors-problems/Finance/6272095-Case-study-of-Integrative-4-Ogrady-apparel-company-Do-you-know-th/ | CC-MAIN-2014-10 | refinedweb | 959 | 63.49 |
On 9/14/07, L.Guo <leaveye.guo at gmail.com> wrote: > Hi ? Haskell's boxed arrays are non-strict, which can cause space leaks when you don't actually need the laziness. The usual quick-&-dirty solution is to switch to unboxed arrays (e.g. IOUArray), which are inherently strict, but they're only available for certain primitive element types. The solution, then, is to make sure you adequately force your thunks before storing them in an array. > update arr p i = do > (_,o) <- readArray arr i > writeArray arr i (True,o*(p-1)/p) Here's a possible fix, though it's untested, and I'm sure there are more elegant ways to write it: update arr p i = do (_, o) <- readArray arr i let val = o * (p-1) / p val `seq` return () -- force the thunk writeArray arr i (True, val) This ensures that the second component of the pair is a value, rather than a thunk. Strictifying data such as numbers and booleans is relatively easy, but things get tricky when you try to force more complicated structures (deepSeq, anyone?). Stuart | http://www.haskell.org/pipermail/haskell-cafe/2007-September/031815.html | CC-MAIN-2014-35 | refinedweb | 186 | 69.72 |
...
CodingForums.com
>
:: Client side development
>
XML
> Accessing the XML file through JavaScript instead of an HTML script
PDA
Accessing the XML file through JavaScript instead of an HTML script
Erica_qt
03-26-2003, 02:06 AM
Hi, I have a script that me and a friend were trying to figure out, to access a .xml file in order to insert information into the HTML file. The following HTML script is what has been being used to access the XML file, however, there are problems when trying to do certain things using this method (In order to save anyone much confusion, I'll only describe exactly what the problems are if it's absolutely necessary, but I think the following information is good enough to describe what we need):
<span id="showPRICE" DATASRC="#albums" DATAFLD="ARTISTNAME"></span>
My friend said that it could be done if it could access the XML file through an equivalent JavaScript rather than HTML script.
There was another post on this forum that I think wants the same thing at:
And on that page, it links to:
But the script on that page is very very confusing. How do I access an individual field in the XML file rather than a whole group? Like I said, we want it to be directly equivalent to this HTML script, but using JavaScript instead:
<span id="showPRICE" DATASRC="#albums" DATAFLD="ARTISTNAME"></span>
liorean
03-26-2003, 02:44 AM
Loading an xml file can be done through several different mechanisms, the one you'll be interested in is likely loading an xml document object into a reference variable.
var
src=[string XMLFile],
doc,
i;
function handleXml(doc){
/*\
| Handle xml document here.
| You can use DOM 1 Core and most of DOM 2 Core.
| Note that you will need to check whether you
| should use namespaced or non-namespaced functions
| if you want to edit the imported xml document.
\*/
}
switch((i=(document.implementation&&document.implementation.createDocument)||top.ActiveXObject||null)){
case ActiveXObject:
doc=new i('Microsoft.XMLDOM');
doc.async=false;
handleXml(doc);
break;
case document.implementation.createDocument:
doc=new i('','',null);
doc.load(src);
doc.onload=function(){handleXml(this)};
break;
default:
alert("User agent lacks xml importation mechanism");
}
(This code is just written and untested, so it might not work without bugfixing. Especially I wonder whether user agents that doesn't support document.implementation will let it pass or throw an error. Is nn4/ie4/op<7/minor browsers interesting for you?)
Erica_qt
03-31-2003, 04:17 AM
I couldn't understand any of that, I'm not too great at programming, so I didn't even know where to start with that...
However, I was browsing through search engines trying to find an answer, and I found EXACTLY what I needed... But I don't know how to make it work slightly different. They only have one group in their XML file... I need many many groups, and to be able to access them individually... Does anyone know what I mean?
This information is in "note.xml"
<?xml version="1.0" encoding="ISO8859-1" ?>
<note>
<to>Tove</to>
<from>Jani</from>
<heading>Reminder</heading>
<body>Don't forget me this weekend!</body>
</note>
and this is in "note.html"
<html>
<head>
<script language="JavaScript"
for="window" event="onload">
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM")
xmlDoc.async="false"
xmlDoc.load("note.xml")
nodes = xmlDoc.documentElement.childNodes
to.innerText = nodes.item(0).text
from.innerText = nodes.item(1).text
header.innerText = nodes.item(2).text
body.innerText = nodes.item(3).text
</script>
<title>HTML using XML data</title>
</head>
<body bgcolor="yellow">
<h1>Refsnes Data Internal Note</h1>
<b>To: </b><span id="to"></span>
<br>
<b>From: </b><span id="from"></span>
<hr>
<b><span id="header"></span></b>
<hr>
<span id="body"></span>
</body>
</html>
Erica_qt
04-01-2003, 12:48 AM
Does anyone know how to do this? Is it too hard, is that why there is no response yet? Or is it just not possible?
liorean
04-01-2003, 01:04 AM
Oh, there's plenty of people here who know how to do it. The reason there's no response before now is not because it's too hard. It's not 'not possible'.
It's just that some things take time to code for. You're asking for something specific enough to require a final functionality but generic enough that we can't be sure what you want. And we're lazy. (And this isn't the most frequented forum, as you can see by the number of threads in it.) Give it a shot, explain the structure of the xml you want to dissect and what you want to read out from it. Explain what you want us to do with the information extracted from the file.
(Oh, just a sidenote, do you know anything about the DOM and how it works? That would make things easier for us.)
Erica_qt
04-01-2003, 04:31 AM
Sorry, I didn't mean to sound impatient. I would wait up to a week without comenting on the fact that there were no replies. Except that I've posted on this forum before (but lost my account and password, so I made a new one) a while back and usually got VERY quick responses, sometimes within minutes. And so that's why I thought it a little unusual that there were no replies yet.
Actually, my friend convinced me to describe the specific problem we were having, but since it was significantly different from this (it is related to the script in this post, but this post isn't necessarily related to it) that I just put it in a new post. But it hasn't gotten any replies. The URL for that post is:
Anyway, the reason we need to be able to access the XML file with javascript is because he figured that he could get the script to work if he made variables equal whatever was in the specific XML fields, THEN insert it into the script.
liorean
04-01-2003, 04:27 PM
Erica if you tell me a few things, I could write a quite simple script doing what you need:
0. What input do you have for telling the script how to handle the xml (or in this case, determining what entry to handle)? Hard coded, cookies, user agent, prompt, links, forms, serverside determination etc.
1. What's the structure of each individual entry in the xml file? (I gather you wanted to get a single entry out of many. Am I right?)
2. When you have read the entry into the javascript, what processing (modification, calculation, etc.) do you want to do?
3. How do you want to output the result?
Try to be as concise as possible in explaining.
Charliers
02-23-2005, 03:53 PM
I understand what you want because I would like to do the same ..
Taking an exemple :
<player>
<name>toto</name>
<age>21</age>
<sex>man</sex>
...
</player>
We see in the exemple given before a javascript code that access to the i-th child of the <player> node..
But if you change the XML file your HTML page will be destroyed then!
What you want is to know how we can directly access the child "name" or "age" .. like that, even if someone add a child to the player node.. your HTML page will still correct!
.. I try to find some exemples, but for the moment, I have nothing!
Frederic.
codegoboom
02-25-2005, 12:12 AM
Uh, there are several ways to reference nodes... here are a couple:
xmlDoc.selectSingleNode("//name").text;
xmlDoc.getElementsByTagName("age").item(0).text;
Just between you & me, the MSXML () reference contains many examples. ;)
mattyod
02-25-2005, 11:03 AM
You might find this thread useful as I have just been going through a similar process :)
Same question in Javascript forums ()
EZ Archive Ads Plugin for
vBulletin
Computer Help Forum
vBulletin® v3.8.2, Copyright ©2000-2013, Jelsoft Enterprises Ltd. | http://www.codingforums.com/archive/index.php/t-17022.html | CC-MAIN-2013-48 | refinedweb | 1,343 | 63.29 |
Since this blog is of a technical nature I plan to be posting more code snippets as time goes on. I obviously want the source code to appear pretty on my blog with all the syntax highlighting that one is used to in modern IDEs (including Visual Studio .NET 2003/2005). I run this blog using WordPress and I have just installed a plugin to take care of the Syntax highlighting called WP-dp.SyntaxHighlighter. It supports many languages and I’ll be interested mainly in the .NET languages. Below is an example of a code snippet in C#
using System; public class ReverseArraySort { public static void Main() { string[] strings = {"beta", "alpha", "gamma"}; Console.WriteLine ("Array elements: "); DisplayArray (strings); Array.Sort (strings); // Sort elements DisplayArray (strings); } public static void DisplayArray (Array array) { foreach (object o in array) { Console.Write ("{0} ", o); } Console.WriteLine(); } } | https://www.seandeasy.com/code-syntax-highlighting-in-wordpress/ | CC-MAIN-2021-31 | refinedweb | 143 | 62.78 |
Erlang
iex
I learned that iex isn't technically a true REPL 5.
elixir
Application logging
I also got to take a deeper foray into application logging. I've been working on a more complex feature for work and would like to be able to track down any causes of bugs so
IO.inspect and the like aren't going to be enough.
It turns out that logging in elixir is actually quite simple. As expected it follows industry practices of having different level support. Check out more at [6],[7].
The latest release of Elixir
A new release of elixir is in release candidate.
Writing documentation
Guards
Calling into functions that can throw
Ran into this
== Compilation error in file lib/vs_integrations/petco/pgr/pet.ex == ** (CompileError) lib/vs_integrations/petco/pgr/pet.ex:11: cannot invoke remote function patient.client/0 inside guards (stdlib) lists.erl:1354: :lists.mapfoldl/3
Associated code
def map_patient_to_pet(patient) when patient.client != nil do ...
You can write your own guards
mix tasks
Environment variables
Discovering nodes
Ecto
Joining multiple tables
Scripting
Real world reference projects
exunit
Running a single test in exunit
It's possible to run a single test in exunit.
mix test /tests/path/to/test/some_test.ex:123
You can create tags for unit tests.
Exmachina
Connection ownership
To spawn or not to spawn
Blogs
- My bad ideas: A blog about erlang and functional programming
- Keathley | https://www.blakedietz.me/blog/2020-01-06/elixir-learnings-week-2/ | CC-MAIN-2021-04 | refinedweb | 236 | 50.73 |
Storage in a Windows 8 App
Apps generate data. Some of them generate a ton of data and others just a few little bits and pieces. Allow me to enumerate your options for storing stuff when you’re working on an app for Windows 8. There are subtle differences between the way storage is done in an HTML/JS app versus a .NET or a C++, but for most of the techniques you’re just accessing the WinRT library so the steps are practically identical.
Before we enumerate the types of storage, let’s talk about the types of data that typically get generated in an app. I’ll break them up into application state, user settings, application data, and user data.
Application State
Application state (or session state) is the data that pertains to what the user is doing in their use of an app. If the user has browsed to the registration page and starting typing their name and address in, then that data is session state. If the user has to drop their tablet (figuratively of course), switch apps, or something else and doesn’t get back to it for some time, then the kind thing (only humane option?) to do is remember their state and restore it when they return.
User Settings
A user has preferences. Your user might want the music in their game turned off. They might want to choose a theme color. They might want to turn on automatic social sharing. These are preferences. They usually take up hardly any space, but it’s they’re really important to your user. The best thing to do is store them in the cloud instead of just on a device so the user feels like they are remembered wherever they go.
Application Data
Application data is the data generated by your app that may have everything in the world to do with your user, but your user is going to assume that the app is holding that data for him and doesn’t want to manage it himself outside of the app. If you installed a task list app, you’d expect it to hold tasks for you, right? That’s app data. The line can be blurry between app data and user data, so read on.
User Data
User data is data generated by the app, but belongs more to the user than the app. The user expects to be able to send the data to a friend, open it in a different program, or back it up to the cloud. User data is everything you find in the libraries – the documents library, the music library, etc.
Implementation
So, let’s talk about how to implement these.
Application state can be stored in WinJS.Application.sessionState. That’s an object that WinJS and Windows handle for you and plays well with the lifecycle of your app. Saving to the sessionState object couldn’t be easier. Just issue a command like…
WinJS.Application.sessionState = { currentPage: "widgets", formFields: { firstName: "Tom", lastName: "Jones" } };
You could do this anytime during the use of your app or you could wait until the app.oncheckpoint event (look on your default.js page for that) and just do it when your app is on it’s way out of the spotlight.
Keep in mind that this is for session data only. Windows assumes that if your user explicitly ends the app, they are ending their session and sessionState is not stored. You also can’t count on it after an application crash, so make sure it’s only transient data that wouldn’t ruin the users day to lose.
User settings are again very important. You have many options for storing them, but only two that I recommend. The first is localSettings and the second is roamingSettings. Only use localSettings if you have good reason not to roam the setting to the cloud. If you use roamingSettings and the user doesn’t have a Microsoft account, it will still store locally. Both of these are accessed from Windows.Storage.ApplicationData.current. You can store a new setting value like this…
localSettings.values["gameMusic"] = "off";
Application data can work much like the user settings technically, but it serves a different purpose. Imagine the task list app I mentioned before. The tasks themselves must obviously be stored and you - the developer - have quite a variety of options. You have to ask yourself a few questions like:
- Does the user need to share the app data with select others?
- Does the user need access to the data on multiple devices?
- Does the data feed any other apps either on the same or another platform?
It’s very possible that just storing data local to the device is plenty. In that case, the localFolder from Windows.Storage.ApplicationData.current. This spot is dedicated to storing data for your app and your app only. No other apps have access to it actually.
If you have a very small amount of application data (less than 100k) then you can use the roamingFolder from the same Windows.Storage.ApplicationData.current. This data will, just like the roamingSettings, be synced to the user’s online profile and back down to any other devices they might log in to.
You have a variety of other options for storing data such as a local database, online database, online user drive, and more, but I’ll save those for another day and another post.
Finally, we’ll talk about user data. Unlike application data, users will expect to have ownership of their user data. When a user creates a spreadsheet, this is not data that just exists inside of Excel. The user expects to have that spreadsheet in their documents and be able to work with it (share it, rename it, organize it, …) outside of Excel.
If your app is one that will work with user data, then you need to pick a file format and create the association. This is done in the package.appxmanifest where you’ll also need to add a capability to access the users documents. It’s quite a easy thing to use the open and save file dialogs from your app and the user will love having full access not only to his documents, but also all apps he has installed that implement the FilePicker contract.
That’s quite enough on storage for now. Perhaps some of the following locations from within the Windows Dev Center will be helpful to you…
Storage and state reference
Windows.Storage namespace
WinJS.Application.sessionState object
Manage app lifecycle and state
Optimizing your app's lifecycle
Have fun. | https://docs.microsoft.com/en-us/archive/blogs/codefoster/storage-in-a-windows-8-app | CC-MAIN-2020-10 | refinedweb | 1,108 | 64.1 |
Type: Posts; User: noobofcpp
Update : It turns out I forgot to do
mWindowTitle = appName;
in my app initialization function.Foolish me. Sorry for the trouble. Have a nice day folks.
Update: I tried on simple console app and it works fine.This confusing me.
#include <iostream>
#include <sstream>
int main()
{
int i = 0;
std::ostringstream ss;
Tried to my update my window title with some performance metrics for my vulkan renderer with std::ostringstream. When i run it tells there's access violattion leading to xtring file funtion size_t...
So if creating new thread is costly then i should use a thread pool right? can you recommend a good thread pool library and a free profiler tool to check function execution time
Just tried to implement multithreading rendering with vulkan and the result is dissappointing that multithreading code is 4x slower than singlethread. Tried multithreading on my cpu ray tracer code...
thanks for the explaination sir. i think i understand
after you asked to measure execution time, i did test with std::chrono::steady_clock::now() on it and emplace_back is slightly faster. Sorry didnt thought to test it before. So the emplace_back is...
Well i just figured out there's a emplace_back method than does same thing as push_back after 4 years messing around with c++. Which one is faster or which one should I use. Currently i use...
I understand. Thank you for knowledge you give me.
Hyper threading is one of my CPU features, so i think yes. There are 8 CPU graph on task manager.
with four threads it took 0.0625277 seconds while 8 threads it took 0.0441792 seconds35617
@wolle. Time taken to render with one thread is 0.133174 seconds while the multi threaded one is 0.0426739 seconds. What about Open MP? According to this post...
@wolle my cpu is Intel Core i7 6700hq. It has 4 cores
Thank you 2kaud
@2kaud can you show me example of variable locking
@2kaud. Thank you boss
I just wrote a simple ray tracer with multi threading. I divide the rendering process into 8 threads. The result is 3.5 times faster than using single thread.My question is, is it correct use of...
you're right mr wolle. That's actualy source of the problem. The vector object. distracted me from the the actual problem. Ahh how stupid am I. Thank you everyone for your time and effort to reply...
The debugger show the frameIndex value is 0, while the mMSAAFramebuffers vector size is 2. I'm sure the problem is not that. It throws read access violation even i'm trying to print out the...
I'm completely clueless what's going on here.Why it keep throwing read access violation.
35397
Here's the header file.
#pragma once
#include "Renderer\VulkanApplication.h"
#include...
Why they use some kind of crazy naming convension and lot of underscores?
// constructors
vector_impl(_Mytype_t% _Right)
{ // construct by copying _Right
for (size_type _Idx =...
Thank you Mr VictorN it turns out i was mixing Debug and Release DLL
I recently encoutered weird situation where in Debug build the program got access violation at....while in Release build it runs without problem.How this such condition happens.Could be compiler bug...
I only got first texture show up.
What's wrong with this my code,I can't find where's the mistake.
int main()
{
sf::ContextSettings settings;
settings.majorVersion = 4;...
Thank you so much 2kaud your help gave me hint I need to do some opengl initialization procedure for the DLL and now it's. | https://forums.codeguru.com/search.php?s=27de2b3cdc7d217d463991e073b04603&searchid=22823124 | CC-MAIN-2022-33 | refinedweb | 595 | 78.45 |
Charting Feyn graphs
Project description
Feynplots
A package to see what's going on inside graphs produced from a QLattice. A QLattice is a quantum mechanics simulator produced by Abzu that produces models for datasets in an evolutionary process. You can read more about the QLattice here. Feyn is the package used to interact with the QLattice and you can find more about getting started with it here.
A graph produced from the QLattice typically looks like so
This is a model for the California housing dataset. Each interaction takes either one or two variables as input and has a single output. This means that we can plot each interaction. Let's do that!
Here's a couple of comments on this plot
Each dot corresponds to a datapoint in the training set. The colour corresponds to the actual value of the target variable.
The x-axis corresponds to the variable x0;
The y-axis corresponds to the variable x1;
The scale on each axis the scale of each feature;
The contour lines correspond to the value of the output at the (x0,x1) coordinate.
Here's a small summary of how to use this package.
from feynplots import GraphChart graphplot = GraphChart(g) #initiates the chart instance graphplot.model_ev(data) #evaluates every interaction at every datapoint graphplot.plot(figsize = (30,20)) #plots the figure
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/feynplots/0.0.2/ | CC-MAIN-2022-05 | refinedweb | 253 | 64.81 |
There.
Normally in an RSS feed, the content of a blog item is not delivered as XML, but rather as HTML that is enclosed within the RSS <description> tag, and is massaged so that its HTML tags don't conflict with the enclosing XML tags. Since the content I create for my blog really is valid XML, I added the <body> element to make the content available as pure XML for use by other XML applications. In particular, I envisioned storing the <body> content in a database and then running XPath queries to do structured searches of the blog entries.
Months passed, things happened, and I never got around to creating that structured-search application. Then, last week, I took another look at my feed and suddenly it seemed wrong. I thought that I had not correctly assigned both the <body> element, and its contained elements, to the XHTML namespace. After conferring with Sam Ruby, a member of IBM's Emerging Technologies Group and one of the developers of an alternative syndication specification (provisionally called Pie, Echo, and Atom, but not yet finally named), I realized that I had, in fact, gotten it right in the first place.
It's not just me, lots of people trip over this stuff. Some notable experts — including Sean McGrath, CTO of Propylon in Dublin, Ireland — argue that namespaces should be avoided for that reason.
Clearly there's something counterintuitive about XML namespaces. Here are two oft-cited truisms that suggest different interpretations of that fact.
1. You never forget how to ride a bicycle.
2. Use it or lose it.
Some might say that mastery of XML namespaces is like riding a bicycle: Yes, it's counterintuitive, but the trick is impossible to forget once you learn it.
Others might say that mastery of XML namespaces is the kind of skill that atrophies with disuse.
Who would be right? We hope for the former, evidence so far suggests the latter, but I don't think we can decide yet. In my case, I haven't really ridden the bicycle yet. Although I'm publishing a mixed-namespace format, I'm not yet using it in a namespace-aware way.! » | http://www.infoworld.com/d/applications/xml-namespaces-and-training-wheels-730 | crawl-002 | refinedweb | 366 | 61.06 |
Give your boss the illusion of managing you… with pidgin and dbus
by sudharsh
Oh yeah!. With the power of DBus and libpurple APIs it is possible to give your boss the illusion of managing you. Just run the following script (under WTFPL). Tested with jabber accounts in a live office environment :P.
#!/usr/bin/env python # By Sudharshan S, released under WTFPL import dbus import gobject import time class PointyHairedBoss: def __init__(self, boss_id, source, frequency=30): self.boss_id = boss_id self.source = source self.frequency = frequency bus = dbus.SessionBus() _pidgin_proxy = bus.get_object("im.pidgin.purple.PurpleService", \ "/im/pidgin/purple/PurpleObject") self.purple = dbus.Interface (_pidgin_proxy, "im.pidgin.purple.PurpleService") # FIXME: account_id = self.purple.PurpleAccountsGetAllActive()[0] self.boss_conversation = self.purple.PurpleConversationNew(1, account_id, self.boss_id) self.boss_im = self.purple.PurpleConvIm(self.boss_conversation) print self.boss_im def start_nonsense(self): question_list = open(self.source) for q in question_list: self.purple.PurpleConvImSend(self.boss_im, q) time.sleep(self.frequency) if __name__ == "__main__": # Change the jabber id and the path to your questions, with an optional frequency o = PointyHairedBoss("foo@gmail.com", "questions") o.start_nonsense()
Advertisements
Awesome. So nice. :)
just great.
Nice. You should also tell people that the script expects a file called “questions” in the current directory with a question on each line :)
Logs or it didn’t happen
I don’t have logs but I was hung upside down from the ceiling when my boss caught the act…
pics or it didnt happen
wtf? is this 4chan now?
A telepathy version of the script someone?
Logs or it didn’t happen..
You should modify the script so that you can see the results of your fun :-)
It opens up an IM window in pidgin anyway. So you do get to see the replies :P
That’s actually pretty brilliant… too bad my boss sits right around the corner from me. He’d come over and answer the questions in person…
Thanks for introducing me to the WTFPL.
Its also a valid Free Software license :P
Compatible with the GPL too i believe.
[…] coming across this article today on Reddit, I decided to cook up a little AppleScript to accomplish the same task for us Mac […]
carbon dating or it didnt happen
Not as cool as Python but I made an AppleScript version in case anyone was interested:
[…] Give your boss the illusion of managing you… with pidgin and dbussudharsh.wordpress.com […]
[…] Give your boss the illusion of managing you… with pidgin and dbus « Random Rants of a n… – […]
hell I did this in 10 minutes with applescript and adium. Funny thing is Adium uses the pidgin libraries, yet is SO MUCH THE MORE AWESOME.
Here is some of my output…
Would you like me to insert the screen and erase the bell?
Don’t you think I should blow on the server to rotate the document?
Can I populate the jack if I login to the application?
Unfortunately it seems like he installed an 8ball application to answer me…
Concentrate and ask again.
It is decidedly so.
Ask again later.
Here’s the code for an eight-ball responder.
#!/usr/bin/python
# By Vineel A, released under WTFPL
import dbus
import gobject
import time
import random
from dbus.mainloop.glib import DBusGMainLoop
def recieve(account, sender, message, conversation, flags):
## print ‘Account: ‘, account
## print ‘Sender: ‘, sender
## print ‘Message: ‘, message
## print ‘Conversation:’, conversation
## print ‘Flags: ‘, flags
answers = [‘As I see it, yes.’,
‘It is certain.’,
‘It is decidedly so.’,
‘Most likely.’,
‘Outlook good.’,
‘Signs point to yes.’,
‘Without a doubt.’,
‘Yes.’,
‘Yes – definitely.’,
‘You may rely on it.’,
‘Reply hazy, try again.’,
‘Ask again later.’,
‘Better not tell you now.’,
‘Cannot predict now.’,
‘Concentrate and ask again.’,
“Don’t count on it.”,
‘My reply is no.’,
‘My sources say no.’,
‘Outlook not so good.’,
‘Very doubtful.’]
answer = random.choice(answers)
bus = dbus.SessionBus()
obj = bus.get_object(‘im.pidgin.purple.PurpleService’,
‘/im/pidgin/purple/PurpleObject’)
purple = dbus.Interface(obj, ‘im.pidgin.purple.PurpleInterface’)
account_id = purple.PurpleAccountsGetAllActive()[0]
boss_conversation = purple.PurpleConversationNew(1, account_id, sender)
boss_im = purple.PurpleConvIm(boss_conversation)
time.sleep(1)
purple.PurpleConvImSend(boss_im, answer)
DBusGMainLoop(set_as_default=True)
bus = dbus.SessionBus()
bus.add_signal_receiver(recieve,
dbus_interface=’im.pidgin.purple.PurpleInterface’,
signal_name=’ReceivedImMsg’)
loop = gobject.MainLoop()
loop.run()
Praise me for posting this to reddit:
hi reddit.. thanks :D
[…] Give your boss the illusion of managing you… with pidgin and dbus « Random Rant… […]
Sup3rkiddo, you’ve grown up now… *sigh*
Awesome, btw :D
[…] Shared Give your boss the illusion of managing you… with pidgin and dbus « Random Rants of a n00b […]
[…] Give your boss the illusion of managing you… with pidgin and dbus « Random Rant… […]
[…] blogger: Sudharshan S derived inspiration from this strip to write himself a prank python script to keep the manager in his life ‘busy’ . A pretty neat idea… and with some […]
[…] Give your boss the illusion of managing you… with pidgin and dbus « Random Rants of a n00b […]
Not to be pointing out the obvious but wouldn’t it be easier to write these as Pidgin and Adium plugins?
True, but more brownie points are reserved for not-so-straightforward solutions when it comes to annoying your bosses ;)
For hottest information you have to pay a visit world-wide-web
and on world-wide-web I found this website as a most excellent
website for most recent updates.
Hi there, its good piece of writing concerning media print, we all know media is a wonderful source of data.
Hello! I could have sworn I’ve visited this website before but after looking at some of the posts I realized it’s new to me.
Nonetheless, I’m definitely happy I stumbled upon it and I’ll be bookmarking
it and checking back frequently!
What’s up friends, its wonderful article regarding
educationand completely defined, keep it up all the time.
I every time used to read piece of writing in news papers but now as I
am a user of web thus from now I am using net for posts, thanks to web.
Excellent post. I was checking constantly this
blog and I’m impressed! Very useful info specially the last part
:) I care for such info much. I was looking for this particular information for a very long time.
Thank you and best of luck.
With the right kind of info, the correct spirit and the
proper resources, you is going to be set into making a flourishing Internet business.
Affiliate programs are free to join and
several residual income opportunities will run you less than $100 to begin.
Lynn Van – Dyke’s site is now in the top 1% of all websites as outlined by Alexa.
That is a great tip especially to those fresh to the blogosphere.
Brief but very precise information… Appreciate your sharing this one.
A must read article!
Yes! Finally someone writes about whatsapp para iphone 4.1.
Way cool! Some extremely valid points! I appreciate you penning
this write-up plus the rest of the website is very good.
If you want to obtain much from this article then you have to apply such methods to your
won web site.
Hi there to every one, it’s in fact a pleasant for me to visit this web page, it
contains valuable Information.
I love it when ijdividuals get togfether and share opinions.
Great site, keep it up!
Pretty! This has been a really wonderful post.
Thanks for providing these details.
Hey there, You have done an incredible job. I’ll definitely
digg it and personally recommend to my friends. I am confident they will be benefited
from this web site.
At last! Someone with real exretpise gives us the answer. Thanks! | https://sudharsh.wordpress.com/2009/06/30/give-your-boss-the-illusion-of-managing-you-with-pidgin-and-dbus/ | CC-MAIN-2018-13 | refinedweb | 1,275 | 58.99 |
I figured it out>
Here is the solution for anyone interested.
Adobe Dreamweaver * Adding media objects
Or, go to Insert->Media-> and select the location of the applet .class file
--- Update...
I figured it out>
Here is the solution for anyone interested.
Adobe Dreamweaver * Adding media objects
Or, go to Insert->Media-> and select the location of the applet .class file
--- Update...
Yes,that is what am asking.I already can load it in an html page by writing the html code in notepad and running in my browser.I want to be able to do same using Dreamweaver.That is, insert the...
How do i get the applet running in dreamweaver? just like i would in notepad
Hi.Does anyone have any idea how to load applets in Dreamweaver?
the only options for codebase are ftp, http, https
Yeah, the if () {} statement is inside a try catch statement, i just forgot to include it in my question.
Question is a little bit elementary, but i just need a programmer to programmer explanation.
For example:
if (number < 1 || number > 100 )
throw new InvalidInputException();
...
Yeah, i know i need to use the new keyword.The confusion is in the constructor
MyDate today = new MyDate(...with regards to my example,what goes in here?...);
Strings don't work
Let's say i have this code:
import java.util.Date;
public class MyDate {
Date newDate;
public MyDate(Date date) {
Thanks.That explains a lot
ehm,
index1 = the index of the first element (row) in the array, say numbers[0][1], no?
index 2 = the index of the first element (column) in the array
numbers = the array
numbers[i]= the current...
Let say i have this code:
public class ArrayDemo {
public static void main (String[]args) {
int [][] numbers = {{5,3,2},{7,5,3}};
int sum=0;
int index1;...
cool.
--- Update ---
Found a solution (?) to the problem.
...
ArrayList <Integer> numbers = new ArrayList<Integer>();
int position=0;
I have found that this is the case.
:o Okay.I'll get right to it.
--- Update ---
Ok so am working using Sets now (for the first time) and i discovered it does not allow duplicates which is good.but problem is,when i run the code...
Here is my code which works fine
public class Arrays {
public static void main (String[]args) {
int maxNum= 0;
int minNum = 100;
int position=0;
ArrayList...
Thanks.I have moved away from this problem as i now understand i cannot prevent the random number generator from generating a specific number twice.
Try reading this
Error Message:
use the code tags
[code] ...place code here... [\code]
that way it's easier for people to read your code and help direct you towards a solution.
Let say i have this code:
public class MyRandomStuff {
public static void main (String[]args) {
int [] randomNumbers = new int[5];
for (int i=0; i<randomNumbers.length; i++) {
...
Check the location of your .java files, are there .class files there also?
--- Update ---
Also, check out this video on Youtube and follow the instructions carefully.
...
Finally got help from my tutor.This is one possible way to do it.
import java.util.*;
public class ArrayTest{
public static void main (String[]args){
Scanner input = new Scanner(System.in);...
import java.util.*;
public class ArrayTest2 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int[] numbers = {8, 11, 19, 84};
That was VERY helpful
This is what i eventually did
import java.util.*;
public class ArrayTest {
public static void main (String[]args) {
Scanner input = new Scanner(System.in);
int [] number...
import java.util.*;
public class ArrayTest {
public static void main (String[]args) {
Scanner input = new Scanner(System.in);
int [] number = new int[5];
... | http://www.javaprogrammingforums.com/search.php?s=af24fbc9d5d0a903ce1bea90a48d1365&searchid=1461401 | CC-MAIN-2015-14 | refinedweb | 615 | 68.47 |
leap.bitmask 0.5.3-4-g1e456b0
The Internet Encryption Toolkit: Encrypted Internet Proxy and Encrypted Mail.
=======
*your internet encryption toolkit*
.. image::
:target:
.. image::
.. image::
**Bitmask** is the multiplatform desktop client for the services offered by
`the LEAP Platform`_.
It is written in python using `PySide`_ and licensed under the GPL3.
Currently we distribute pre-compiled `bundles`_ for Linux, OSX and Windows.
.. _`PySide`:
.. _`the LEAP Platform`:
.. _`bundles`:
Read the Docs!
------------------
The latest documentation is available at `LEAP`_.
.. _`LEAP`:
License
=======
.. image::
Bitmask is released under the terms of the `GNU GPL version 3`_ or later.
.. _`GNU GPL version 3`:
.. :changelog::
History
-------
2014
====
0.5.3 June 27 -- the "encrypt ALL THE THINGS" release:
++++++++++++++++++++++++++++++++++++++++++++++++++++++
- Disable EIP if the helper files were not installed. Closes #5818.
- Install helpers to /usr/local for bundle. Closes #5741.
- Improve how pinned providers are handled by hardcoding it instead of
expecting them to be in the config. Closes #4733.
- Remove deprecated policy files. Closes #5651.
- Install helper files only if standalone=True. Related to #5625
- Use installer helper from within bundle path. Related to #5634
- Pin Riseup as a provider. Closes #5783.
- Update the bundled binaries to their path if their sha256 is not
correct. Closes #5759.
- Use a dict instead an object to ease later serialization of
ProviderConfig.
0.5.2 June 6 -- the "are we there yet" release:
+++++++++++++++++++++++++++++++++++++++++++++++
- Unblock local multicast IPs from linux firewall, to allow SSDP and
Bonjour/mDNS to work.
- Add support for gnome-shell polkit agent. Closes #4144, #4218.
- Update username regex to support the same as webapp. Closes #5965.
- Wrong error message for username too short. Fixes #5697.
- Cleanup and refactor username/password validators.
- Fix EIP autostart failing. Closes #5721.
- Block ipv6 traffic for the moment. Closes #5693
- Fix bug with ipv6 blocking that caused block to not get removed from
firewall when Bitmask quit.
- Bring firewall down when switching EIP off. Closes #5687
- Add OPENVPN_BIN_PATH for OSX so that EIP starts properly.
- Allow usernames to end in a digit.
- Improve signal handling in the mainwindow and wizard.
- Enable UI when OpenVPN bin is not found, plus check before starting
EIP. Fixes #5619.
- Properly set the userid for SMTP.
- Update EIP UI if it fails to download the config.
- Make use of cmdline in psutil backwards-compatible. Closes #5689
- Add versioning support to bitmask-root.
- Show flag of country for eip exit node, if available. Related #1232
- Fix nameserver restoring. Closes #5692
- Warn user if resolvconf cannot be found.
- Refactor Keymanager to backend. Closes #5711.
- Cleanup backend from hacks. Closes #5698.
- Improve wait and quit process.
- Move soledad password change to backend.
- Move Mail logic to backend.
- Separate imap/smtp logic from conductor.
- Refactor SoledadBootstrapper to backend. Closes #5481.
0.5.1 May 16 -- the "lil less leaky" release:
+++++++++++++++++++++++++++++++++++++++++++++
- Use non blocking dialog so the Pastebin result does not block the
app. Closes #5404.
- Handle provider setup problems and show an error to the user. Closes
#5424.
- Disable providers combo box during check and enable combo or line
edit depending on radio button. Closes #5495.
- Hide the bandwidth widget and update status icon if the openvpn
process is killed. Closes #5497.
- Change password doesn't work. Closes #5540.
- Hide services that the current logged in provider does not
have. Closes #5550.
- If we don't have a provider supporting that service we hide the
actions along with the widgets. Related to #5550.
- Client mistakenly says that traffic is routed in the clear. Closes
#5551.
- Avoid user getting errors if he does a 'ctrl-c' on the wizard during
the first run. Closes #5559.
- Download/upload rates were displayed backwards in the widget
rate. Closes #5563.
- Fix unable to login issue. Closes #5581.
- Hardcode paths for openvpn if STANDALONE=True. Related: #5592
- Increase waiting time to wait for polkit agent to be up. Closes:
#5595
- Use openvpn hard restart. Closes: #5669
- Enable Turn ON button for EIP whenever possible (json and cert are
in place). Fixes #5665, #5666.
- Fix Logout button bottom margin. Fixes #4987.
- Properly finish the Qt app before stopping the reactor.
- Let OpenVPN run its course when a ping-restart happens. Fixes #5564.
- Refactor smtp logic into its bootstrapper.
- Add flag to allow the user to start the app hidden in the
tray. Closes #4990.
- Refactor: move SRPAuth to the backend. Closes #5347.
- Refactor: move EIP to backend. Closes #5349.
- Use PySide @Slot decorator instead of 'SLOT' docstring. Closes
#5506.
- Advanced key management: show a note to the user if the provider
does not support Encrypted Email. Closes #5513.
- Gracefully handle SIGTERM, with addSystemEventTrigger twisted
reactor's method. Closes #5672.
- Hide the main window on quit as first thing and show a tooltip to
inform that we are closing.
- Increase expiration life of a pastebin log from 1 week to 1 month.
- Use iptables firewall. Closes: #5588
- Refactor Soledad initialization retries to SoledadBootstrapper.
- Refactor EIPBootstrapper to the backend. Closes #5348.
- Add flag to skip provider checks in wizard (only for testing).
- Add support for Mate's polkit agent.
0.5.0 Apr 4 -- the "Long time no see" release:
++++++++++++++++++++++++++++++++++++++++++++++
- Fix logging out typo, closes #4815.
- Improve logout action, related to #5131.
- In case of soledad bootstrap error (e.g.: network failure), re run
all the setup process.
- Correct resolvconf usage. Avoids permanent break of
resolv.conf. Closes #4633.
- Disable and stop EIP when you set EIP as disabled in the preferences
dialog. Closes #4670.
- Advanced Key Management: add view for stored public keys. Closes
#4734.
- Reset registration error and input widgets if the user goes back to
provider selection in wizard. Closes #4742.
- Disconnect signals before closing the wizard. Closes #4817.
- Fix logout error message, display it similarly to other errors in
the app. Closes #4942.
- Client should say 1 unread email, not emails. Closes #4952.
- Update menu name in Wizard. Closes #4984.
- Config help menu: do not use an empty password. Closes #4985.
- Handle wizard close correctly. Closes #4986.
- Fix "Something went wrong with the logout" misleading error in every
logout. Closes #4995 and #5071.
- Use version checks in the wizard when the user choose to use an
existing provider. Closes #5048.
- Move error messages from srpauth to the GUI and refactor
signals. Closes #5219.
- Fix psutil version to avoid conflicts with gnupg required
version. Closes #5309.
- Update bitmask url in PKG-INFO. Closes #5395.
- Disable 'next' button if the checks passed but the provider is
changed. Closes #5396.
- Do not start soledad and mail if the mail service is
disabled. Closes #5411.
- Don't escape logs for pastebin. Closes #5433.
- Handle closed Soledad database on quit, speedup exit. Closes #5130.
- Catch shutdown errors. Closes: #5313
- Properly reset imap session on logout. Closes: #4925
- Sync Soledad before bootstrapping mail only if the key for the user
is not found locally. Otherwise, defer to thread and
continue. Closes #5083.
- Set as selected default for the eip preferences window the item
selented in the bitmask main window. Closes #5153.
- Cancel login does not work or needs to be pressed twice. Closes
#4869, #4973.
- Fail gracefully against keyring import errors.
- Update requirements and code for the new psutil version.
- Use Bitmask icon instead of LEAP's for the super user dialog in
OSX. Fixes #4273.
- Workaround a bug in Ubuntu where the menu is not displayed in the
global menu bar. Fixes #5420.
- Wizard: select by default the use of an existing provider if we have
configured at least one. Closes #4488.
- Add in-app indication of how to connect to local imap and
smtp. Closes #4530.
- Warn the user on incompatible api error.
- Warn the user if is using an old app version. Closes #4636.
- Minor UI changes: re-arrange main window so that the login widget is
at the top and preferences are available under the menu.
- Disable Advanced Key Manager import feature since it's experimental
and may cause data loss. Closes #4877.
- Offline mode for debugging. Closes: #4943
- Add pastebin button to upload logs from the logs window to ease bug
report. Closes #5163.
- Add support for self signed certs. Closes #5391.
- Add hotkey for the Help menu. Closes #5401.
- Add --repair-mailboxes command line option. It will be needed to
migrate existing account after a data schema changes, like it will
be happening for 0.5.0. Closes #4792.
- Make first Soledad sync wait for EIP to come up after logging in.
Fixes #4885.
- Ensure IMAP flushes data to disk before quitting. Closes #5095.
- Update key manager auth to interact with webapp v2. Fixes #5120.
- Handle invalid auth tokens when syncing Soledad, and show an error
on the GUI. Fixes #5191.
- After connecting EIP check for DNS resolution and warn the user on
error. Closes #5301.
- Display domain for provider the user has just logged in. Fixes
#4631.
- Add ability to import a maildir into a local mailbox.
- Add ability to write mail logs to a separate file.
- Show hash info in About bitmask (for debian versions).
- Add the appname in the reported version string.
- Move/refactor SRPRegister to the backend.
- Add ability to nice application via environment variable.
- Refactor ProviderBootstrapper out of the UI modules to a Backend
module, obscuring all the details.
- Remove qt4reactor as a dependency.
2013
====
0.3.8 Dec 6 -- the "Three week child" release:
+++++++++++++++++++++++++++++++++++++++++++++++
- Make the preferences window selects the current selected provider in
the login widget even if the user is not logged in. Closes #4490.
- Support non-ascii characters in a provider name. Closes #4952.
- Disable Turn On EIP in tray if the service is disabled. Closes #4630.
- Do not show the generic message "EIP has stopped" since it's
redundant. Fixes #4632.
- Avoid attempt to install policykit file in debian package. Closes:
#4404
- Properly close Soledad at quit time. Fixes #4504.
- Fix soledad bootstrap subtasks order. Closes #4537.
- Add --nobind as a VPN parameter to prevent binding on local
addresses. Fixes #4543.
- Disable Turn On EIP until we have an usable provider. Closes #4523.
- Load provider if the wizard was rejected and the setup was
completed.
- Disable Turn On EIP if the "Encrypted Internet" service is disabled.
Closes #4555.
- If EIP service is disabled display 'Disabled' instead of 'You need
to login to use Encrypted Internet'.
- Disable eip-config until we have configured the provider. Closes
#4422.
0.3.7 Nov 15 -- the "The Big Lebowsky" release:
+++++++++++++++++++++++++++++++++++++++++++++++
- Use custom SysTray in order to display per-service tooltip easily.
Closes #3998.
- Escape logs with html contents so they get displayed in plaintext
on the log viewer. Closes #4146.
- Wizard now behaves correctly in provider selection after click
'cancel' or 'back'. Closes #4148.
- Handle Timeout errors during register process. Closes #4358.
- Send user's key to nickserver whenever keymanager is
initialized. Closes #4364.
- Password change dialog is now properly enabled. Closes #4449.
- Remember provider checks in wizard, do not re-run them if the user
goes back and forth through the wizard. Closes #3814 and #3815.
- Improve compatibility with OSX Mavericks. Fixes #4379.
- Initialize mail service with the userid after login, to allow
multiple accounts. Closes: #4394
- Give SMTP the current logged in userid. Related to #3952.
- Do not wait for initial soledad sync to complete to launch mail
services. Closes: #4452
- Add hint to user about the duration of the key generation. Closes
#3958.
- Add advanced key management feature. Closes #4448.
- Properly log EIP status changes.
0.3.6 Nov 1 -- the "bạn có thể đọc này?" release:
+++++++++++++++++++++++++++++++++++++++++++++++++
- Fix problem changing a non-ascii password. Closes #4003.
- Enable password change in the client only if it has started the
correct services. Closes #4093.
- Select the current logged in provider in the preferences
window. Closes #4117.
- Fix problem with non-ascii paths. Closes #4189.
- Capture soledad boostrap errors after latest soledad changes.
- Refactor keyring handling and make it properly save user and
password. Fixes #4190.
- Properly stop the imap daemon at logout. Fixes #4199.
- Align left the speed and transferred displays for EIP. Fixes #4204.
- Remove autostart eip option from settings panel, rely on last used
setting. Closes #4132.
- Add support for requests 1.1.0 (raring). Closes: #4308
- Refactor mail connections to use state machine. Closes: #4059
- Add a command to setup.py to freeze the versions reported under
debian branches. Closes: #4315
- Use coloredlogs handler if present (for development, not a
requirement).
- Hide the GUI for services that are not supported on the set of
configured providers. Closes #4170.
0.3.5 Oct 18 -- the "I can stand on one foot" release:
++++++++++++++++++++++++++++++++++++++++++++++++++++++
- In case of Soledad failure, display to the user that there was a
problem. Closes #4025.
- Widget squashing problem in wizard checking a new provider. Closes
#4058.
- Remember last domain used to login. Closes #4116.
- Display first run wizard, regardless of pinned providers. Closes
#4143.
- Show EIP status 'ON' in the systray tooltip when is
connected. Related to #3998.
- Catch u1db errors during soledad initialization.
- Disable --danger flag on release versions. Closes #4124.
- Display mail status in the tray icon as an enabled item. Fixes
#4036.
- Only show N unread Emails when N > 0. Fixes #4098.
- Hide login error message when the user interacts with the widgets
to fix the potential problem. Fixes #4022.
- Add call to `make` to the bootstrap script.
- Improve GUI based on QA rounds. Fixes #4041 and #4042.
- Increase the amount of retries for the authentication request
session. Fixes #4037.
- Rename EIP to Encrypted Internet in its preference panel. Fixes
#4057.
- Disable stdout redirection on Windows for the time being since it
breaks the bundle.
- Default UP_SCRIPT and DOWN_SCRIPT to None and only add that
parameter to the vpn command if not None.
- Look for gpg on windows with the .exe extension.
- Change the Util menu to be named File in OSX. Fixes #4039.
- Show more context information in the logs. Closes #3923.
- Automate internationalization process, create project file
dynamically on make. Closes #3925.
- Add support for running lxde polkit agent. Closes #4028.
- Added Vietnamese and English (United Kingdom) translations.
- Implements openvpn observer. Closes: #3901
- Reconnect EIP if network down. Closes #3790
- Reconnect if tls-restart. Closes: #3262
0.3.4 Oct 4 -- the "look at my new makeup" release:
+++++++++++++++++++++++++++++++++++++++++++++++++++
- Fixes a bug where you cannot login to a different provider once
you logged in to another one. Fixes #3695.
- Resets the session for every login attempt. Related to #3695.
- Avoid error message if --version flag is used. Closes #3914.
- Fix a bug in which failing to authenticate properly left
connection in an unconsistent state. Closes: #3926
- Avoids errors due to the EIP switch button and action being
enabled when we do not have a configured provider. Closes: #3927
- Add more verbose error handling during key generation and syncing.
Helps diagnose: #3985; Addresses in part: #3965
- Choose one gnupg binary path that is also not a symlink. Closes
#3999.
- Refactor vpn launchers, reuse code, improve implementations,
update documentation. Closes #2858.
- Add preferences option to enable/disable the automatic start of
EIP and selection of the EIP provider to auto start. Closes #3631.
- Force cleanlooks style for kde only if the app is running from
bundle. Closes #3981.
- Add a dropdown for known providers in the wizard. Closes #3995.
- Separate pinned providers from user configures ones. Closes #3996.
- Improve error handling during soledad bootstrap. Closes: #3965.
Affects: #3619, #3867, #3966
- Implement new UI design. Closes #3973.
- Make the initial provider cert verifications against our modified
CA-bundle (includes ca-cert certificates, for now). Closes: #3850
- Use token header for authenticated requests. Closes #3910.
- Do not distinguish between different possible authentication
errors. Fixes #3859.
- Do not start Soledad if Mail is not enabled. Fixes #3989.
- Allow window minization on OSX. Fixes #3932.
- Properly stop the smtp daemon. Fixes #3873.
0.3.3 Sep 20 -- "the calm after the tempest" release:
+++++++++++++++++++++++++++++++++++++++++++++++++++++
- Remove execution bits in text files in bundle. Closes #3617.
- Use generic bad username/password message instead of specific ones when
the user uses incorrect data during login. Closes #3656.
- Fix LoggerWindow saving more than one line return per line in the logs
file. Closes #3714.
- Fix keyring imports so we do not get import errors. Closes: #3759
- Catch logout problem, display a user message and allow log back in after a
successful logout if there was a logout error before. Closes #3774.
- Fix path prefix helper for the bundle and add regresion tests. Closes #3778.
- Prevent dialogs closing the app when it has been minimized to the tray. Closes #3791.
- Do not try to install resolv-update globally. Closes: #3803
- Inconsistent hide/show main window from tray action. Closes #3821.
- Allow SMTP to start even when provider does not offer EIP. Closes: #3847
- Fix username case problem at register/login. Closes #3857.
- Catch IndexError on `first` utility.
- Update git repo name in docs. Closes: #3417
- Move STANDALONE flag to a module and unify get_path_prefix queries.
Closes #3636.
- Display the Encrypted Internet and Encrypted Email status in the systray
tooltip. Closes #3758.
- Tasktray menu changes, closes #3792.
- Remove the provider domain item (e.g. bitmask.net).
- Rename the EIP status menu items to be more descriptive.
- Change the EIP status menu items from disabled menu items
to submenus with children.
- Move the EIP action menu items under the EIP status submenu tree.
- Adds ``--version`` flag. Closes: #3816
- Refactors EIPConnection to use LEAPConnection state machine. Closes: #3900
- Include resource files and ui in the distrubution tarball. Closes: #3825
0.3.2 Sep 6 -- the "no crashes or anything" release:
++++++++++++++++++++++++++++++++++++++++++++++++++++
- Fix up script in non-bundle linuces. Closes: #3450
- Logout stops imap and smtp services. Closes: #3553
- Properly daemonize polkit-gnome-authentication-agent. Closes: #3554
- Set appropiate error on login cancel. Closes #3582.
- Fix gateway selection problem. Closes 3595.
- Fix typo in wizard: stablish -> establish. Closes #3615.
- Display Encrypted Mail instead of mx in wizard. Closes #3657.
- Fix save logs to file dialog freezing. Closes #3675.
- Complain if setup.py is run with python3. Closes: #3711
- Enable preferences option in systray. Closes #3717.
- Make soledad emit failed signal for all kinds of socket error.
- Allow to selectively silence logs from different leap components. Closes: #3504
- Add option to select gateway manually in the preferences panel. Closes #3505.
- Add preferences option to select the enabled services of a provider. Closes #3534.
- Refactor basic password checks. Closes #3552.
- Use dirspec instead of plain xdg. Closes #3574.
- Remove last page from wizard. Closes #3616.
- Display encrypted mail status in the tray. Closes #3659.
0.3.1 Aug 23:
+++++++++++++
- Replace wizard images with the rainbow mask. Closes #3425.
- Update leap.common minimum version needed.
- Set the standalone flag before it's being used. Fixes #3426.
- Stop the twisted reactor adding the stop call to the call chain
instead of stopping it directly. Fixes #3406.
- Allow soledad initialization to retry if it times out. Closes:
#3413
- Activate window when setting it visible. Also display Hide/Show
message in the tray icon taking into account the window
activation. Fixes #3433.
- Do not start IMAP daemon if mail was not selected among the
services. Fixes #3435.
- Reword RECONNECTING state of openvpn. Fixes #3429.
- Improve OpenVPN detection by searching for a specific leap-only
string in the command line. This makes it possible to run other
VPN instances while also using EIP. Fixes #3268 and #3364.
- OSX: Check for the tun.kext existence in /Library/Extensions
instead of /System/Library/Extensions. Fixes #3271.
- Use DELETE /1/logout to properly logout. Fixes #3510.
- Make the poll interval bigger to improve openvpn's internal
behavior. If it gets queried too many times per second, it's
behavior won't be good. Fixes #3430.
- Transforms usernames to lower case before they are used in the
registration and authentication. Closes #3541.
- Add filter option to the logger window. Closes #3407.
- Add a preference panel that lets you change your password. Closes
#3500 #2798 #3533.
- Move all client code into its own namespace
(leap.bitmask). Closes: #2959
- Make mail fetch interval in imap service configurable via
environment variable. Closes: #3409
- Update to new soledad package scheme (common, client and
server). Closes #3487.
- Fetch incoming mail when mail client logs in. Closes: #3525
- Add first draft of the UI for Encrypted Mail. Closes #3499.
0.3.0 Aug 9:
++++++++++++
- Add missing scripts does not stop if a command fails, also warns
the user if there was an error. Closes #3294.
- Replace 'Sign Out' with 'Log Out' and 'User' with
'Username'. Closes #3319.
- Verify cacert existence before using it. Closes bug #3362.
- Properly handle login failures. Closes bug #3401.
- Bugfix, avoid getting negative rates. Closes #3274.
- Raise window when setting it as visible. Fixes #3374
- Fail gracefully when the events port 8090 is in use by something
else. Fixes #3276.
- Validate the username in the login form against the same regexp as
the wizard registration form. Fixes #3214.
- Update text from the tray menu based on the visibility of the
window. Fixes #3400.
- Add check for outdated polkit file. Closes #3209.
- Add support for multiple schemas so we can support multiples api
versions. Closes #3310.
- Rebrand the client to be named Bitmask. Feature #3313.
- Add cancel button to login. Closes #3318.
- Add multiple schema support for SMTP. Closes #3403.
- Add multiple schema support for Soledad. Closes #3404.
- Update Transifex project name and translators'
documentation. Closes #3418.
- Add check for tuntap kext before launching openvpn. Closes: #2906
- Accept flag for changing openvpn verbosity in logs. Closes: #3305
- Add imap service to the client. Closes: #2579
- Add pyside-uic support inside the virtualenv. This way it won't
fail to 'make' if the virtualenv is activated. Closes #3411.
- Reintegrate SMTP relay module. Closes #3375
- Reintegrate Soledad into the client. Closes #3307.
- Support bundled gpg. Related to #3397.
- Set the default port for SMTP to be 2013.
- Display a more generic error message in the main window, and leave
the detailed one for the log. Closes #3373.
0.2.4 Jul 26:
+++++++++++++
- Use the provider CA cert for every request once we have it
bootstrapped (TOFU). Closes #3227.
- Make calls to leap.common.events asynchronous. Closes #2937.
- Always logout when closing the app if the user previously signed
in. Fixes #3245.
- Make sure the domain field in provider.json is escaped to avoid
potential problems. Fixes #3244.
- Fix incorrect handling of locks in Windows so that stalled locks
do not avoid raising the first instance of the app. Closes: #2910
- Use traffic rates instead of totals. Closes #2913
- Allow to alternate between rates and total throughput for the
virtual interface. Closes: #3232
- Reset rates/totals when terminating connection. Closes #3249
- Fix a bug in the displayed magnitude for the up/down traffic rates
and totals.
- Force Cleanlooks style if we are running in a KDE environment, so
that it doesn't load potentially incompatible Qt libs. Fixes
#3194.
- Wrap long login status messages to 40 characters. Fixes #3124
- Workaround a segmentation fault when emitting a signal with its
last parameter being None. Fixes #3083.
- Added IS_RELEASE_VERSION flag that allows us to use code only in
develop versions. Closes #3224.
- Try to terminate already running openvpn instances. Closes #2916
- Linux: Dynamically generate policy file for polkit. Closes #3208
- Workaround some OpenVPN problems with priviledge dropping and
routing. Fixes #3178 #3135 #3207 #3203
0.2.3 Jul 12:
+++++++++++++
- Adapt code to Soledad 0.2.1 api.
- Fix Main Window briefly display before the wizard on first
start. Closes Bug #2954.
- Bugfix: Remember should not be automatically set to
checked. Closes #2955.
- Bugfix: reload config if switching to a different provider. Closes
#3067.
- Bugfix: logger window's toggle button reflects window
state. Closes #3152.
- Set timeout for requests to 10 seconds globally, configurable from
leap.util.constants. Fixes #2878.
- Bugfix: display error message on registration problem. Closes
#3039.
- Make wizard use the main event loop, ensuring clean termination.
- Use cocoasudo for installing missing updown scripts.
- Bugfix: Systray Turn ON action fails because is not correctly
enabled/disabled. Closes #3125.
- Bugfix: wrong systray icon on startup. Closes #3147.
- Bugfix: parse line return in the logger window. Closes #3151.
- Do not log user data on registration. Fixes #3168.
- Add --log-append eip.log to windows EIP launcher options to save
the logs in case of any problems. Fixes #2054.
- OSX: Make the install_path relative to the launcher path instead
-f absolute.
- OSX: Fix icon display in cocoasudo.
- OSX: Raise window when showing if running on OSX.
- Bugfix: EIP status button moved to status panel.
- Check if there is no gateway to use and display correct
message. Close #2921.
- Reorder tray icons according new design. Closes #2919.
- Redirect stdout/stderr and twisted log to the logger. Closes
#3134.
- Improve LoggerWindow colors for easier debugging.
- Move the key manager to its own repository/package.
0.2.2 Jun 28:
+++++++++++++
- Add support for the kde polkit daemon
- Handle 'Incorrect Password' exception (keyring)
- Select the configured domain in the providers combo box. Closes
#2693.
- Remember provider along with the username and password. Closes
#2755.
- Close the app on rejected wizard. Closes bug #2905.
- Only use the Keyring when it's using a known good backend. Closes
#2960
- Update implementation and semantics of the supported and available
services by a provider. Closes bug #3032.
- Only show the question mark for a check being done if the previous
-ne passed. Fixes #2569.
- Fix main client window not restoring after minimized into
systray. Closes #2574
- Set EIP different status icons depending on OS. Closes #2643.
- Reimplement openvpn invocation to use twisted ProcessProtocol
- Add runtime requirements checker, verifies that the requirements
are installed and in its correct versions. Closes #2563
- Add centraliced logging facility, log history in a window. Closes
#2566
- Improve wizard, hide registration widgets (labels, inputs, button)
and only display a message. Closes #2694
- Clarify labels through the app (use of EIP)
- Check if the provider api version is supported. Closes feature
#2774.
- Autoselect VPN gateway based on timezone. Closes #2790.
- Disable vpn disconnect on logout. Closes #2795.
- Improve gateway selector based on timezone. It allows to use
multiple gateways in openvpn for redundancy. Closes #2894.
- Use cocoasudo in place of osascript for osx privilege escalation
during openvpn launch.
- Clicking in the tray icon will always show the context menu
instead of activating the window under certain
circumstances. Closes #2788
- Autostart EIP whenever possible. Closes #2815
- Update test suite, run_scripts and requirements to run smoothly
with buildbot.
- Add a copy of the processed requirements to util/
- Display the default provider configured in the systray menu. Close
#2813
- Make the login steps be a chain of defers in order to be able to
have more cancel points for the whole procedure. Closes #2571
- Linux: check for up/down scripts and policy files and ask user for
permission to install them in a root-writeable location. Used from
within bundle or for broken installations.
- Integrate SMTP-Relay into the client.
- Integrate Soledad and KeyManager.
- Move the KeyManager from leap.common to leap-client.
- Only use one systray icon, repesenting the status for EIP. Closes
#2762
- Properly set the binary manifest to the windows openvpn
binary. Closes #203
- OSX: Add dialog with suggestion to install up/down scripts if
these not found. Closes: #1264, #2759, #2249
- Workaround for PySide breaking with multiple inheritance. Closes
#2827
- Refactor login to its own widget and remove Utils menu. Closes
#2789
- Refactor the status bits out of the MainWindow to its own
StatusPanelWidget. Closes #2792
- Save the default provider to be used for autostart EIP as
DefaultProvider in leap.conf. Closes #2793
- Cleanly terminate openvpn process, sending SIGTERM and SIGKILL
after a while. Closes #2753
- Use twisted's deferToThread and Deferreds to handle parallel tasks
- Use a qt4 reactor for twisted, for launching leap twisted
services.
0.2.1 May 15:
+++++++++++++
- Rewrite most of the client based on the insight gained so far.
- Deselecting the remember checkbox makes the app not populate
user/password values on the login widget. Closes #2059
- Rewording of setup steps in wizard, to make them more meaningful
to the non-technical user. Closes #2061
- Fix typo in wizard.
- Fix multiple drawing of services if going back.
- Make registration errors show in red.
- Add a warning if EIP service needs admin password. Addresses part
-f #2062
- Make traffic indicators display fixed precision. Closes #2114
- Do not hide the application if the user right clicked the system
tray icon.
- Sanitize network-fetched content that is used to build openvpn
command.
- Avoids multiple instances of leap-client. Each new one just raises
the existing instance and quits.
- Use dark eip icons os osx. Closes #2130
- Moves BaseConfig to leap.common.config. Closes #2164
- Add handling for ASSIGN_IP state from OpenVPN in the mainwindow.
- Emit events notifying of the session_id and uid after
authentication so other services can make use of it. Closes #1957
- Working packaging workflow with rewritten client, using
pyinstaller and platypus.
- Remove network checks temporarily until we find a good way of
doing it, and a good way to deal with them.
- Saves the token to allow token authenticated queries.
- Turn "leap" into namespace package, move common files to
leap_common package that can be shared by other LEAP projects.
- Support standalone configurations for distribution in thumbdrives
and the like.
- Add support for requests < 1.0.0
- Tests infrastructure, and tests for crypto/srpauth and crypto/srpregister.
- Documentation updated for 0.2.1 release.
- Docstrings style changed to fit sphinx autodoc format.
- Add a simple UI to notify of pending updates.
- Add Windows support.
- Try to install TAP driver on Windows if no tap device is preset.
- Author: Kali Kaneko
- Documentation: leap.bitmask package documentation
- Download URL:
- Keywords: Bitmask,LEAP,client,qt,encryption,proxy,openvpn,imap,smtp,gnupg
- :: Communications :: Email
- Topic :: Communications :: Email :: Post-Office :: IMAP
- Topic :: Internet
- Topic :: Security
- Topic :: Security :: Cryptography
- Topic :: Utilities
- Package Index Owner: kali
- DOAP record: leap.bitmask-0.5.3-4-g1e456b0.xml | https://pypi.python.org/pypi/leap.bitmask/0.5.3-4-g1e456b0 | CC-MAIN-2016-26 | refinedweb | 4,942 | 69.18 |
.
Generating Live tiles for Windows Phone from Live Data
A cool new feature of Windows Phone 8 is new wide live tiles for your apps on the home screen. This article explains how to deliver live images and setup the client side to periodically update the tile images without having to use push notifications and an expensive cloud host.
Windows Phone 8
Introduction
Windows Phone lets you create live tiles with text and/or graphics, and the focus of this article is to use a live graphic data feed (such as weather or traffic data) and generate multiple sizes of images that will be used as background for live tiles. There are two options to update tiles with Windows Phone.
Push Notifications
The first option is to use Push Notifications for Windows Phone. To update a tile using push notifications, your app has to register with the push service and you need to setup your server side to generate the notifications when necessary. The advantage of this approach is that you can update the tiles whenever necessary (within the limits of the push service). To actively generate notifications, you need to keep a process running on the server to generate the notifications, such as an azure worker. Also it means that your app requires cloud hosting instead of a simple web hosting, and there can be quite an order of magnitude in the pricing. ASP.NET web hosting start at couple of dollars a month (flat rate), whereas cloud hosting is at least 5 times that amount (and rate depends on usage).
Client side updates
The second option is to rely on client side updates. Luckily, Windows Phone provides a ShellTileSchedule class for this purpose. ShellTileSchedule lets you schedule tile updates to update tiles periodically and is a perfect way to keep your tiles up to date. With this option, all you need is a web server that can deliver images in specific dimensions.
Setting up the server side
Finding a host
All your need is an ASP.NET host. The asp.net website has a long list of options that start at couple of dollars a month.
The MVC4 Project
To provide the live tiles, you need a web server that will serve the tiles to client. .NET provides many options for web projects, and we will use here the MVC model because it makes it easy to configure URLs and send images using code. The first step is to create a new MVC 4 project that will be published to your web server.
In the options, all you need is an empty template.
ImageResizer
Because the live tiles have to be delivered in specific sizes, the original data source has to be transformed and possibly converted (e.g. Windows Phone doesn't like GIFs). In this example, we will use ImageResizer.
ImageResizer is a powerful library for manipulating images on the server side. It lets you do all kinds of operations such as cropping, resizing and even adding watermarks.
Adding ImageResizer to your project
The easiest way to add ImageResizer to your project is to use NuGet and search for the ImageResizer package online, or use the Package Manager and type
PM> Install-Package ImageResizer
The live source
To test this app, we will use a live image from the camera at MHB-25 Manh S URW @ Twr Walkwy' in New York that can be accessed at
To deliver it as live tile, we will have to crop it and resize it in two sizes:
- 336 x 336 for small and medium tiles
- 336 x 961 for the wide tile
And according to this article, the image size can NOT exceed 80KB, and download time can NOT exceed 60 sec.
The controller code
We need a MVC controller to generate the images. The default MVC project contains a Controller folder, and the context menu has a wizard to create a new controller.
That class needs one method for the medium icon and another one for the large:
public class NYTrafficController : Controller
{
public FileResult Icon()
{
return Resize(336, 336);
}
public FileResult IconLarge()
{
return Resize(336, 691);
}
public FileResult Resize(int height, int width)
{
var uri = "";
var rsSettings = new ResizeSettings() { Format = "jpg", MaxHeight = height, MaxWidth = width };
rsSettings.Mode = FitMode.Crop;
rsSettings.Scale = ScaleMode.Both;
Config c = Config.Current;
var wc = new WebClient();
wc.CachePolicy = new System.Net.Cache.RequestCachePolicy(System.Net.Cache.RequestCacheLevel.NoCacheNoStore);
var dt = wc.DownloadData(uri);
using (var ms = new MemoryStream(dt))
{
var mStream = new MemoryStream();
c.CurrentImageBuilder.Build(ms, mStream, rsSettings);
mStream.Seek(0, SeekOrigin.Begin);
return new FileStreamResult(mStream, "image/jpeg");
}
}
}
The final URLs for these icons will be:
The actual resizing and cropping are done by the Resize method. The live URL is configured there and the WebClient' is configured to download the image every time and disable caching. The default settings of the jpeg will generate an image of about 45k for the wide one and about 26k for the medium one which should download fast and are under the limits.
Setting up your app
Now that you have your website ready to deliver live data, all that is left is to configure one or many tiles for your app.
Manifest configuration
The first step is to set your app with FlipTiles. It seems that only FlipTiles do support remote URIs for the images. Also you need to provide icons for each tile size.
The secrets of ShellTileSchedule
There is one not well known constructor of ShellTileSchedule that takes a ShellTile and a ShellTileData. The ShellTileData argument is the only way to define all properties of a tile and including backgrounds with remote URLs. When this constructor is used, the RemoteImageUri property of the ShellTileSchedule will be ignored.
Limitations
The minimum update interval for the live tile is 1 hour. If your app needs more frequent updates to the background, the only alternative is to use push notifications.
Adding ShellTileSchedule to your app
The easiest location to configure the default tile is in the constructor as shown below:
public MainPage()
{
InitializeComponent();
var tileId = ShellTile.ActiveTiles.FirstOrDefault();
if (tileId != null)
{
var tileData = new FlipTileData();
tileData.BackBackgroundImage= new Uri(@"");
tileData.WideBackBackgroundImage = new Uri(@"");
var trafficTileSchedule = new ShellTileSchedule(tileId, tileData);
trafficTileSchedule.Recurrence = UpdateRecurrence.Interval;
trafficTileSchedule.Interval = UpdateInterval.EveryHour;
trafficTileSchedule.Start();
}
} | http://developer.nokia.com/community/wiki/index.php?title=Generating_Live_tiles_for_Windows_Phone_from_Live_Data&oldid=201092 | CC-MAIN-2014-42 | refinedweb | 1,044 | 60.45 |
- Author:
- gregb
- Posted:
- May 2, 2010
- Language:
- Python
- Version:
- 1.1
- admin user userprofile
- Score:
- 1 (after 1 ratings)
Helper function which adds some niceties to the auth/user admin views. Needs django 1.2 to work.
Usage
Define a UserProfile class and set
AUTH_PROFILE_MODULE as per the django docs
In your admin.py file (or anywhere else) add the following:
from models import UserProfile from [path to snippet] import upgrade_user_admin upgrade_user_admin(UserProfile)
More like this
- Multiple User subclasses custom Auth backend by ungenio41 4 years, 11 months ago
- convenience parent class for UserProfile model by willhardy 7 years, 4 months ago
- More information about users and groups in user admin by buriy 8 years, 1 month ago
- Alternative to User.get_profile() by jpwatts 8 years, 5 months ago
- group_required decorator by msanders 7 years ago
Please login first before commenting. | https://djangosnippets.org/snippets/2007/ | CC-MAIN-2016-36 | refinedweb | 141 | 51.89 |
OpenSSL + Swift: Everything You Need to Know
.
Tid-Bits of Knowhow
OpenSSL was first released in 1998 under the premise to create a free set of encryption tools for code used on the internet. Since then it has become one of the most well known (and distributed) open-source projects.
OpenSSL is a C based security library focusing on computer network security. Due to the large implementation suite it provides, from SSL and TLS to hash and cipher functions, OpenSSL has trusted implementations of some of the most popular cryptographic functions.
First Timers and OpenSSL (Background)
Integrating OpenSSL’s library into your macOS or iOS app can be…..well…a bit more than tricky when you haven’t used a library like it before.
The first thing to note is that you should never use an untrusted, precompiled version of OpenSSL in your app. Anyone can modify the source of OpenSSL with malicious code and distribute that library. Be sure to only download the library from a trusted source (i.e.) and check the hash of your download.
Static or Dynamic Linking
So we download the source. We need to compile it into a usable library. There are two options we have: a Static Library or a Dynamic Library. Like anything in Computer Science, the answer to “Which should I use?” is It Depends.
Dynamic Libraries (also known as Shared Libraries) are
.so files (or
.dylib files in macOS). All code relating to the library is this file and it is referenced by your program at run-time. Static Libraries are
.a files. Any program using a static library takes a copy of the code from the static library and makes it part of the programs compiled binary — the library becomes part of the code and is one of the first things loaded when starting the application.
Dynamic Libraries have the benefit of reducing duplicate code — if two applications want to reference the same library, they can. And an update to a system dynamic library can allow applications to always use the latest version. Static Libraries, on the other hand, increase the overall size of the binary, however, this also means that code is connected at compile time and there is no additional run-time loading overhead. All the code is just there.
Both have advantages or tradeoffs. In the interest of this guide, I have a business requirement to stay on the same version of OpenSSL for licensing purposes, therefore I am using static linking for the library (as my code will then always use the same version of the code library).
Now to macOS (The Good Stuff) 🔐
File System Structure and git
Create a folder for the OpenSSL libraries and associated file to be located in. I created an
OpenSSL folder at the top level of my project directory:
CryptoExample
└ OpenSSL/
└ .gitkeep
└ CryptoExample/
└ CryptoExample.xcodeproj
I add a
.gitkeep file so git will keep this directory, but we will ignore all other files in that directory in our
.gitignore:
# gitignore
OpenSSL/*
!OpenSSL/.gitkeep
Building for macOS
For most projects, we can build for the i386 and x86 architectures and then combine those builds into a single library. The below script will download a version of OpenSSL (1.1.0g in this case) from their website and run a SHA256 checksum to confirm the download has not been tampered with:
(Note: run the script from your project directory)
After running the script the
OpenSSL folder will contain the
libcrypto.a and the
libssl.a libraries as well as the LICENSE file and
include directory (which includes all the header files for OpenSSL).
Configuring your Xcode Project
This is most likely the reason why you are here. You have your libraries, include headers, but how do you link everything together so you can utilize OpenSSL in your project?!
After running the above shell script your file hierarchy should look something like this:
Target Build Settings
- Under your target’s Build Settings edit
LIBRARY_SEARCH_PATHSto include:
$(PROJECT_DIR)/OpenSSL/lib.
- Set
HEADER_SEARCH_PATHSto include:
$(SRCROOT)/OpenSSL/include.
ModuleMap
Now we create a Swift ModuleMap in order to let the compiler know what C files we want to be associated with a custom module. Here we will call the module
OpenSSL for simplicity, however, it can be called anything.
1. Create a
shim.h file. This is an import header file which imports all OpenSSL files we need to expose.
2. Create a custom
module.modulemap :
3. Head back to your target’s Build Settings and edit
IMPORT_PATHS to include:
$(SRCROOT)/$(TARGET_NAME). This will tell the compiler to look in our project folder for custom module maps.
4. Finally, you can
import OpenSSL (we called the module ‘OpenSSL’) into any Swift file requiring it’s usage.
Your final project hierarchy may look like the following:
build_openssl.sh
CryptoExample
└ AppDelegate.swift
└ Assets.xcassets
└ Base.lproj
└ Info.plist
└ Modules
└ module.modulemap
└ shim.h
└ ViewController.swift
CryptoExample.xcodeproj
OpenSSL
Using Swift (and the problems that arise)
Now we can successfully import our OpenSSL module (note that we could have named it anything). Now we run into some issues with Swift which we do not face when using Objective-C.
OpenSSL is written in C and makes use of macros. Swift, by nature, can not access C macros directly. This makes dealing with some C libraries, like OpenSSL a bit tricky. One declaration in the library is
X509 which is essentially just a pointer. We can use an
OpaquePointer without issue, and I create a typealias for readability.
Take a look at the example below of how direct OpenSSL to Swift language interaction works.
Alternatives
Swift can make dealing with OpenSSL a bit harder than usual. If you find this to be too daunting, you have the option of wrapping all this logic in Objective-C, or exposing C declarations via Objective-C functions which can be called from Swift.
Let’s say you have the C macro to convert a hex value (e.g.
0xff0000) to an NSColor:
#define UIColorFromRGB(rgbHex, alphaValue) \
[NSColor colorWithRed:((float)((rgbHex >> 16) & 0xFF))/255.0 \
green:((float)((rgbHex >> 8) & 0xFF))/255.0 \
blue:((float)((rgbHex >> 0) & 0xFF))/255.0 \
alpha:alphaValue]
In Objective-C the macro can be wrapped in a function and then imported to Swift:
+ (NSColor *)colorFromMacro:(int)rgb alpha:(float)alpha {
return NSColorFromRGB(rgb, alpha);
}
Licensing
First off, I’m no lawyer. I’m a programmer with an internet connection and the requirement to cover our butts. That being said, it is good to know how and where you can use OpenSSL.
OpenSSL is fairly permissive, allowing you to include the frameworks in your application without much issue. The
LICENSE outlines exact usages, but some highlights are:
- Your code must include the copyright notice for the code (located in the LICENSE file).
- You can not use “OpenSSL” in your product name.
- Perhaps the most important: Any redistributions of the framework or advertising materials mentioning the use of OpenSSL must include the following acknowledgment:
“This product includes software developed by the OpenSSL Project
for use in the OpenSSL Toolkit ()"
Essentially, if you use OpenSSL in your project, you should include this statement in a “Legal” section of your application.
For full details, be sure to consult your
LICENSE file included in your OpenSSL folder. | https://medium.com/@joncardasis/openssl-swift-everything-you-need-to-know-2a4f9f256462 | CC-MAIN-2019-43 | refinedweb | 1,213 | 64.51 |
Revision history for CLI-Dispatch 0.19 2014/03/31 - ::Help died if . was in the PATH (DJERIUS++) 0.18 2014/03/29 - switched to Path::Tiny internally 0.17 2013/02/05 - subcommand ("script.pl cmd subcmd args...") support, thanks to Diab Jerius 0.16 2012/11/06 - ::Command->new now accepts a hash of options so that you can write ->new(%opts)->run(@args) . 0.15 2012/08/01 - Log::Dump is not loaded when you provide your own "log" method. 0.14 2011/11/05 - finer log control with --debug and --logfilter options 0.13 2011/06/01 - use the first brief description found in the INC 0.12 2010/12/19 - production release; no code changes 0.11_03 2010/12/18 - encoding tweak for help 0.11_02 2010/10/02 - make sure classes are unloaded after their availability are confirmed (except those that are loaded before the check) 0.11_01 2010/10/02 - use more Try::Tiny 0.10 2010/09/29 - no code changes - added Try::Tiny dependency, hoping to catch test errors correctly 0.09 2010/09/23 - added run_directly method, which would be handy if you prefer writing a set of independent scripts to writing one dispatcher script. 0.08 2010/08/09 - now CLI::Dispatch can accept multiple namespaces in which it looks for subcommands. - noted an example to provide a subcommand aliases. 0.07 2010/04/17 - added a usage method 0.06 2010/04/02 - support inline packages to pack everything in a script file 0.05 2009/07/15 - Now you can add a "check" method to a command to see if it is really available for a user (if the command dies there due to the lack of recommended modules etc, the dying message will be shown in the commands list). (rjbs++) 0.04 2009/07/10 - should always parse .pod file if it exists (tokuhirom++) 0.03 2009/05/16 - better error handling (not to show pod with an unexpected error) 0.02 2008/11/17 - explicitly camelize the first argument for 'Help' command 0.01 2008/11/17 - initial release | https://metacpan.org/changes/distribution/CLI-Dispatch | CC-MAIN-2015-27 | refinedweb | 354 | 77.84 |
.NET class library overview
.NET APIs include classes, interfaces, delegates, and value types that expedite and optimize the development process and provide access to system functionality. To facilitate interoperability between languages, most .NET types are CLS-compliant and can therefore be used from any programming language whose compiler conforms to the common language specification (CLS).
.NET types are the foundation on which .NET applications, components, and controls are built. .NET includes types that perform the following functions:
Represent base data types and exceptions.
Encapsulate data structures.
Perform I/O.
Access information about loaded types.
Invoke .NET security checks.
Provide data access, rich client-side GUI, and server-controlled, client-side GUI.
.NET classes that implements the interface.
Naming conventions
.NET.Generic.List<T> represents the
List<T> type, which belongs to the
System.Collections.Generic namespace. The types in System.Collections.Generic can be used to work with generic collections.
This naming scheme makes it easy for library developers extending .NET to create hierarchical groups of types and name them in a consistent, informative manner. It also allows types to be unambiguously identified by their full name (that is, by their namespace and type name), which prevents type name collisions. Library developers are expected to use the following convention when creating names for their namespaces:
CompanyName.TechnologyName
For example, the namespace
Microsoft.Word conforms to this guideline.
The use of naming patterns to group related types into namespaces is a .NET. This namespace includes classes that represent the base data types used by all applications, for example, Object (the root of the inheritance hierarchy), Byte, Char, Array, Int32, and String. Many of these types correspond to the primitive data types that your programming language uses. When you write code using .NET types, you can use your language's corresponding keyword when a .NET base data type is expected.
The following table lists the base types that .NET supplies, briefly describes each type, and indicates the corresponding type in Visual Basic, C#, C++, and F#., use the .NET API Browser to browse the .NET Class Library. The API reference documentation provides documentation on each namespace, its types, and each of their members.
See also
Feedback
Submit and view feedback for | https://docs.microsoft.com/en-us/dotnet/standard/class-library-overview | CC-MAIN-2022-27 | refinedweb | 369 | 52.15 |
Configuring Sybase ASE database access and creating the Sybase ASE Database Environment involves the following tasks.
Configuring Sybase ASE database access with the volume manager that you are using:
If you are using Solstice DiskSuite/Solaris Volume Manager, see How to Configure Sybase ASE Database Access With Solstice DiskSuite/Solaris Volume Manager.
If you are using VERITAS Volume Manager (VxVM), see How to Configure Sybase ASE Database Access With VERITAS Volume Manager.
Creating the Sybase ASE database environment
Configure the disk devices for the Solstice DiskSuite/Solaris Volume Manager software to use.
For information about how to configure Solstice DiskSuite/Solaris Volume Manager, see Sun Cluster Software Installation Guide for Solaris OS.
If you use raw devices to contain the databases, run the following commands to change each raw-mirrored metadevice's owner, group, and mode.
If you do not use raw devices, do not perform this step.
If you create raw devices, run the following commands for each device on each node that can master the Sybase ASE resource group.
Specifies the name of the disk set
Specifies the name of the raw disk device within the metaset disk set
Verify that the changes are effective.
Go to How to Create the Sybase ASE Database Environment.
Configure the disk devices for the VxVM software to use.
For information about how to configure VERITAS Volume Manager, see Sun Cluster Software Installation Guide for Solaris OS..
Specifies the name of the resource group. This name can be your choice but must be unique for resource groups within the cluster.
Specifies an optional comma-separated list of physical node names or IDs that identify potential masters. The order here determines the order in which the nodes are considered as primary during failover.
Verify that the changes are effective.
Reregister the disk device group with the cluster to keep the VxVM namespace consistent throughout the cluster.
Go to How to Create the Sybase ASE Database Environment.
The. | http://docs.oracle.com/cd/E19528-01/819-0701/ciahbddd/index.html | CC-MAIN-2016-50 | refinedweb | 324 | 54.52 |
You will learn
You will learn how to use Python script to send sensor data to SAP Cloud Platform. If you get stuck with this you can skip to the next chapter and use someone else’s device to show its sensor data in your app.
Send the CPU usage data to SAP IoT Application Enablement via SAP Cloud Platform IoT service for Neo environment
You will learn how to use Python script to send sensor data to SAP Cloud Platform. If you get stuck with this you can skip to the next chapter and use someone else’s device to show its sensor data in your app.
Your computer, which is going to play a role of the IoT device, should have:
- Python - a programming language:
-
requests - HTTP library for Python:
-
psutil - the (process and system utilities) is a cross-platform Python’s library:
- connection to Internet, ideally without proxy
If you need to install above fresh these steps describe what you need to do:
On a Mac python 2 is already installed by default. Only the library manager pip and the additional libraries have to be installed with these steps:
- Request privileges with the Privileges app
- Connect to the internet without a proxy (e.g. mobile phone hot spot)
- In the terminal app do the following:
- Enter
unset https_proxy
- Enter
sudo easy_install pip
- Enter
pip install requests
- Enter
pip install psutil
On the PC follow these steps:
Python 2.xinstaller (you need version
2.x, not
3.y)
cmdfrom the Start Menu
python27directory (might be called different in your version)
Scriptssubdirectory
pip install requests
pip install psutil
cd ..) to the directory where you installed python
python -vto check that python is running and which version you have installed
On your computer, create a file
computer_iotdevice_cpu.py and paste the following Python code into it.
import requests # import psutil # import time, sys, platform hostiotmms = 'iotmmsa2667617c.hana.ondemand.com' apiiotmmsdata = '/com.sap.iotservices.mms/v1/api/http/data/' msgtypeid = 'dc88bf65edae02a05da7' deviceid = '591188FC5CEF41_fake_3E9D5AE3F641429BB5' authtoken = '7461f8d7385_fake_179d36fcfd8' url = "https://"+hostiotmms+apiiotmmsdata+deviceid def readsensors(): global d_pctCPU d_pctCPU = psutil.cpu_percent(percpu=False, interval = 1) return def postiotneo (): global d_pctCPU s_pctCPU = str(d_pctCPU) d_tstamp = int(round(time.time())) s_tstamp = str(d_tstamp) print("\nValues to post: ", d_pctCPU, d_tstamp) payload = "{\"mode\":\"sync\",\"messageType\":\""+msgtypeid+"\",\"messages\":[{\"cpu_usage\":"+s_pctCPU+",\"cpu_type\":\"generic\",\"_time\":"+s_tstamp+"}]}" headers = { 'content-type': "application/json", 'authorization': "Bearer "+authtoken, 'cache-control': "no-cache" } print("Payload to post: ", payload) response = requests.request("POST", url, data=payload, headers=headers) print(response.status_code, response.text) return try: while(True): readsensors() postiotneo() time.sleep(2) except KeyboardInterrupt: print("Stopped by the user!")
Save the file. On a PC save the file to the folder where you installed python.
Update
deviceid and
authtoken variables in the code with IDs you copied in the previous tutorial when creating the thing for your computer.
Run the script with the command.
python computer_iotdevice_cpu.py
If all mentioned prerequisites have been satisfied, then you should see outcome like:
The return code
200 means that the message was received and processed by the IoT service in SAP Cloud Platform.
The return code
202 means that the message was received and queued for processing by the IoT service in SAP Cloud Platform or that the message does not fit the message type requirements.
Codes
4xx and
5xx mean errors.
If you are in a corporate network you might have to put your laptop into another network (e.g. your mobile phone hot spot) to not be hindered by a corporate proxy.
You can press control-c to stop sending data.
Go back to the Thing Modeler application from the previous tutorial. Make sure you have the proper package
computeriotdevice selected and find your computer on the list of Things.
Go to Measured Values and expand
resource_sensors to the
cpu_usage. You should see the value (like
22.2 on the screen shot). It is updated only once a minute, so you may need to wait a bit for it to appear and then to change.
You can find corresponding value in the output of the Python’s script as well.
The power of SAP IoT Application Enablement is in its rich set of APIs available to build powerful customer applications on top of data from devices.
E.g. to check last 5 values posted open following URL in the browser, like Chrome:('591188FC5CEF413E9D5AE3F641429BB5')/sap.iotaehandson2.computeriotdevice:generic_computer/resource_sensors_2?timerange=1H&$top=5
You need to modify the thing id from
591188FC5CEF413E9D5AE3F641429BB5 to your own. Properly formatted URL will return results like this to authorized user.
To better understand IoT Application Enablement APIs you can go to SAP API Hub at and review and execute different APIs in its sandbox. As this sandbox has the same backend you will find your things again here.
Updated 04/04/2018
Contributors Provide Feedback
thecodester
marcuscbehrens
Sygyzmundovych
akula86
10 Min | https://www.sap.com/brazil/developer/tutorials/iotae-comp-sendpy0.html | CC-MAIN-2018-30 | refinedweb | 807 | 54.63 |
On Sat, 2006-08-12 at 15:09 -0700, Elaine wrote: > I am going to be teaching "Introduction to Python > Programming" in the Fall at Foothill College in Los > Altos Hills, CA. This is a 5 quarter unit class for > students who already know one programming language. > > I have been teaching programming for 20 years now, > including Java and C++ as of late. As I prepare this > class, I have some questions that I I am hoping you > can shed some light on. > > 1) Programming Style > > while 1: > x = next() > if not x: break > > I have never allowed students to use break or continue > in any > programming class I have taught. I think of this type > of code as belonging with the dreaded GOTO. > > I find that students who are having difficulty writing > > complex conditions in a loop use multiple if's with > break's > inside the loop instead. Also, it is MUCH easier to > read a > loop if the condition for continuing in the loop is > right up > at the top of the loop where it belongs. > > I have always thought of break and continue as hacks > that > are not compatible with structured programming > techniques. > The only exception is using break in a switch in C, > C++ and > Java. > > However, all Python books seem to contain sample > programs like this one. Do you think that code like > this is desirable? YES. In C you can code while ((c = getchar()) != EOF) <loop body> which combines the assignment and the conditional The equivalent Python code is something like: c = getchar() while c != EOF: <loop body> c = getchar() Because the assignment is a separate statement and not an expression, it cannot be combined with the condition. So the Python consensus seems to be that you are better of with one assignment and embed the condition with a break at the proper spot within the loop. The loop is simply while True: # with newer Pythons c = getchar(1) if c == EOF: break <loop body> In translating from other languages, note that many while loops can become for loops in Python. The while loop above came from K&R page 17, (The C Programming Language, Kernighan and Ritchie) counting lines in a file. A more natural Python translation would use nl = 0 for line in input: nl += 1 print nl Certainly break and continue can be abused. I would normally expect all break and continue testing to be in one section of the while loop so that it looks like while True: <get next whatever we are looping on> <should we skip it: continue> <are we done yet: break> <loop body> I'm glad to see Python getting taught in schools. When my daughter's college decided to stop teaching C++ as the first programming language (the year she took the course), I urged them to seriously consider Python, but they went with Java. > 2) Since this is an introductory class, I am tempted > to leave out "optional" topics like argument matching > modes, walk, map, filter, reduce, apply. Do you think > these are required for any Python programmer? I think the argument matching is too important to skip. For cases like HTTP POST data, passing a dictionary around is pretty convenient when you can pass it using the ** notation. It allows you to code: def celsius(fahrenheit, **kwds): return (fahrenheit - 32) * 5 / 9.0 postdata['celsius'] = celsius( **postdata) So functions can specify just the dictionary keys they care about. My little example imagines an HTML form with a variety of variables that include temperature conversions. Also zip(*args) is the transpose function. This is too handy to omit, but requires covering the single * mode of matching arguments. > > 3) I need to teach a GUI in this class. I would like > something that is easy, standard, and multi-platform. > I am considering Tkinter and Jython. Any opnions on > this? (not from me.) > > Thanks for any answers you might have. > > -Elaine Haight > > > > __________________________________________________ > Do You Yahoo!? > Tired of spam? Yahoo! Mail has the best spam protection around > > _______________________________________________ > Tutor maillist - Tutor at python.org > -- Lloyd Kvam Venix Corp | https://mail.python.org/pipermail/tutor/2006-August/048560.html | CC-MAIN-2016-30 | refinedweb | 682 | 71.44 |
How do you call methods from superclass, like super in classic style ?
2017-05-14 9:45 GMT+02:00 Stephan Houben stephanh42@gmail.com:
FWIW, Javascript itself is moving away from this syntax in favour of a more Python-like syntax based on the 'class' keyword. This was introduced in EcmaScript 2015.
Stephan
Op 14 mei 2017 09:35 schreef "Simon Ramstedt" simonramstedt@gmail.com:
Hi, thanks a lot for your feedback! >
On Sun, May 14, 2017, 00:54 Brendan Barnwell brenbarn@brenbarn.net wrote:
On 2017-05-13 21:07, Simon Ramstedt wrote:
Hi, do you have an opinion on the following?
My general opinion is that imitating JavaScript is almost always
a bad idea. :-)
Wouldn't it be nice to define classes via a simple constructor function (as below) instead of a conventional class definition?
conventional: | classMyClass(ParentClass): def__init__(x): self._x=x defmy_method(y): z=self._x+y returnz |
proposed:
| defMyClass(x): self=ParentClass() defmy_method(y): z=x+y returnz self.my_method=my_method # that's cumbersome (see comments below) returnself |
Here are the pros and cons I could come up with for the proposed method:
(+) Simpler and more explicit.
I don't really see how that's simpler or more explicit. In one
respect it's clearly less explicit, as the "self" is implicit.
(+) No need to create attributes (like
self._x) just to pass
something
from
__init__ to another method.
Attributes aren't just for passing things to other methods.
They're for storing state. In your proposed system, how would an object mutate one of its own attributes? It looks like "x" here is just stored in a function closure, which wouldn't allow easy mutation. Also, how would another object access the attribute from outside (as we currently do with self.x)? You can say we'd only use this new attribute-free approach when we want to pass a constructor argument that's used but never mutated or accessed from outside, but that severely restricts the potential use cases, and all it saves you is typing "self".
Attributes could be added to self just as in conventional classes if they are needed.
Relatedly, how is ParentClass itself defined? I don't see how
you could bootstrap this without having a real class at the bottom of it somehow (as your test script in fact does).
You could bootstrap with an object base class/constructor just as normal classes inherit from object. Also the normal class system should remain in any case in order not to break every python library.
>
(+) Default arguments / annotations for methods could be different for each class instance. Adaptive defaults wouldn't have to simulated with a None.
That seems as likely to be a negative as a positive. Having
different instances with different default values could be confusing. This would even allow different instances to define totally different methods (with if-logic inside the function constructor), which would definitely be confusing.
Different default values for different instances are a corner case but they are already happening by setting default to None. Defining different methods for different instances wouldn't be good but that is also possible with conventional classes (by adding functions to self in __init__).
(+) Class/instance level imports would work.
How often is that really needed?
True, usually it doesn't matter. But when using big packages like tensorflow that take several seconds to load it can be annoying. Its always loaded when importing any library that uses it internally, because of module level imports that should be class/instance level. Even if we just wanted to do --help on the command line and needed that library before argparse for some reason.
(-/+) Speed: The
def-based objects
take 0.6 μs to create while the
class-based objects take only 0.4
μs. For method execution however
the
closure takes only 0.15 μs while the proper method takes 0.22 μs
(script).
I don't think you can really evaluate the performance impact of
this alternative just based on a trivial example like that.
Agree, I don't know really how well this would perform.
(-/+) Checking types: In the proposed example above the returned object
wouldn't know that it has been created by
MyClass.. Another solution would
be to have a special rule for functions with capital first letter
returning a single object to append itself to the list of types of the
returned object. Alternatively there could be a special keyword e.g.
classdef that would be used instead of
def if we wouldn't want
to
rely on the name.
Those special rules sound very hackish to me.
(-) The current syntax for adding a function to an object is cumbersome. That's what is preventing me from actually using the proposed pattern. But is this really the only reason for not using it? And if so, wouldn't that be a good argument for enabling something like below? attribute function definitions: | defMyClass(x): self=ParentClass() defself.my_method(y): z=x+y returnz returnself |
or alternativelymultiline lambdas:
| defMyClass(x): self=ParentClass() self.my_method=(y): z=x+y returnz returnself |
To be honest, from all your examples, I don't really see what
the point is. It's a different syntax for doing some of the same things the existing class syntax does, while providing no apparent way to do some important things (like mutating attributes). I think Python's existing class syntax is simple, clear, and quite nice overall, and creating class instances by calling a function instead of a class doesn't add anything. In fact, even JavaScript has recently added classes to allow programmers to move away from the old approach that you describe here. Also, as I alluded to above, JavaScript is so terrible in so many ways that the mere idea of imitating it inherently makes me skeptical; there's almost nothing about JavaScript's design that couldn't be done better, and most of what it does are things that Python already does better and has done better for years. In short, I don't see any advantages at all to doing classes this way, and there are some non-negligible disadvantages.
Interesting, didn't know that about Javascript. I also don't like Javascript's prototypes very much but thought adding "JavaScript-like" to the title might help explain what I meant.
Leaving the possible replacement for classes aside, do you have an opinion specifically about the following?
def obj.my_function(a, b): ...
as syntactic sugar for
def my_function(a, b): ...
obj.my_function = my_function
In my experience this pattern comes actually up quite a bit. E.g. when working with these "symbolic" machine learning frameworks like theano or tensorflow. Apart from that it mixins very easy.
What do you think are the odds of something like this actually making it into the Python and if greater than 0 in which timeframe?
-- Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown
Python-ideas mailing list Python-ideas@python.org Code of Conduct:
Thanks,
Simon
> >
Python-ideas mailing list Python-ideas@python.org Code of Conduct:
Python-ideas mailing list Python-ideas@python.org Code of Conduct:
-- Antoine Rozo | https://mail.python.org/archives/list/python-ideas@python.org/message/SYSUVDXL6KHSIIGMW5RCM5TILACFZFHC/ | CC-MAIN-2019-47 | refinedweb | 1,214 | 65.93 |
Small plugin to throttle form submit handlers
I’ve started playing with vuelidate and, following the examples there, I’ve had a toast appearing on vuelidation failures. When spamming the Submit button, multiple toasts would appear, with a lot of delay from the initial click. I didn’t like that, so I wrote a plugin that will throttle all methods in components that have their name starting with “handle”, for example
handleSave.
It’s my first “public” plugin, so I’m also looking for some feedback on the code.
import { Utils } from 'quasar' function install (Vue) { Vue.mixin({ beforeCreate () { let self = this let meths = this.$options.methods if (meths) { Object.keys(meths).forEach((k) => { if (!/^handle.*/.exec(k)) return let f = meths[k] meths[k] = Utils.throttle(function (...args) { return f.apply(self, args) }, 2000) }) } } }) } const inBrowser = typeof window !== 'undefined' if (inBrowser && window.Vue) { install(window.Vue) } export default { install }
On the other hande, I’ve initially tried to use
Utils.debounceinstead of
Utils.throttle, but from my testing, the function would be called only after the initial configured timeout expired. | https://forum.quasar-framework.org/topic/283/small-plugin-to-throttle-form-submit-handlers | CC-MAIN-2022-21 | refinedweb | 181 | 51.75 |
The two bumper switches on the front of the robot are
connected to Arduino pins D2, D3, and D4. These lines use
the pinMode statement to specify pins D2 and D3 are
inputs, and D4 is an output. They then use the digital Write
statement to indicate whether the pins are LOW (0V) or
HIGH (5V).
#include <IRremote.h>
#include <Servo.h>
#include “pitches.h”
These lines of code insert (“include”) three additional
files which provide extra features:
• IRremote is a third-party object library that must be
added to the /libraries directory in your Arduino
sketchbook folder.
Though pins D2 and D3 are inputs, they’re made HIGH
to set their internal pull-up resistor. This is necessary for
proper operation of the switches.
Finally, pin D4 is made LOW so that it acts as a 0V
reference for the switches.
• Servo is an object library that’s included with the
Arduino environment.
pinMode(2, INPUT);
pinMode(3, INPUT);
pinMode(4, OUTPUT);
digitalWrite(2, HIGH);
digitalWrite(3, HIGH);
digitalWrite(4, LOW);
pinMode(6, OUTPUT);
pinMode(7, OUTPUT);
digitalWrite(6, LOW);
digitalWrite(7, HIGH);
• pitches.h is an extra file of pre-defined numeric
constants; these constants make it easier to specify a
note to play through the speaker. The pitches.h file is
located with the sketch.
Servo servoLeft;
Servo servoRight;
These two lines are object constructors; they define
two Servo objects that represent the physical servos on the
robot. The names of the objects are descriptive to help you
follow what they are for.
Here, more pins are set as outputs. Pin D6 is made
LOW to act as 0V ground; pin D7 is made HIGH to act as
5V power (this method is acceptable as long as the device
being powered does not draw more than 25-30 mA of
current).
pinMode(12, OUTPUT);
digitalWrite(12, LOW);
int RECV_PIN = 5;
IRrecv irrecv(RECV_PIN);
decode_results results;
These lines define pin D12 as a 0V ground connection
to the piezo speaker. The other lead of the piezo speaker
connects to pin D13.
These lines set up the infrared receiver. Note that the
receiver input is connected to pin D5.
servoLeft.attach(10);
servoRight.attach(9);
volatile int pbLeft = LOW;
volatile int pbRight = LOW;
boolean started = false;
These two lines of code electrically attach the two
servos to pins D10 and D9.
Each of these lines above define a variable used
elsewhere in the sketch. Variables are temporary holders of
data that can be re-used. The int and boolean keywords
specify the kind of variable; in this case, a 16-bit (two byte)
integer (whole number) and a true/false boolean.
irrecv.enableIRIn();
Serial.begin(9600);
These lines of code start the infrared receiver and begin
serial connection back to the PC. Messages sent from the
Arduino are received into the Serial Monitor window.
void setup() {
attachInterrupt(0, hitRight, FALLING);
attachInterrupt(1, hitLeft, FALLING);
Every Arduino sketch must contain a setup function.
This is where any programming statements go that literally
set up the Arduino before things get going. These
statements are executed only once.
The bumper switches use an Arduino feature known as
hardware interrupts to determine when the switches are
activated. Interrupts literally interrupt the action of the
sketch to take time out to run some specified piece of code:
• 0 and 1 specify the interrupt number (0 = pin D2;
1 = pin D3).
• hitRight and hitLeft are the sketch functions that are
called when an interrupt occurs.
• FALLING is a directive that tells the Arduino to trigger
the interrupt when the signal to pin D2 or D3 falls;
that is, changes from HIGH to LOW.
60 SERVO 11.2013
Click to subscribe to this magazine | http://servo.texterity.com/servo/201311/?pg=60 | CC-MAIN-2018-51 | refinedweb | 618 | 63.59 |
Limit the Number of Values in a Multiple Value Field
Rationale
The CMS supports document fields of "type" multiple. By default, the CMS imposes no limit on how many instances of such a field an author can create inside a single document. There may be a need to set an upper limit to the numer of instances of this field inside a single document, f.e. pick no more than 5 related articles for a single news item document.
How to?
You can only configure an upper limit through the Console. Navigate to /hippo:namespaces/<project-name>/<document-type>/editor:templates/_default_/<field-name> and add a property of type Long, called maxitems. The numeric value defines the upper bound on how many instances of the field you may create inside a single document. Such an upper bound is supported for both property-based fields (e.g. fields of type String) and child node-based fields (e.g. compound fields such as Link).
Screenshot
Below screenshot shows how an upper bound of 2 or 3 look in the CMS Document Editor. Note how the upper bound is indicated and, when reached, there is no more Add button.
| https://documentation.bloomreach.com/11/library/concepts/editor-interface/limit-the-number-of-fields-that-can-be-added-to-a-multiple.html | CC-MAIN-2020-34 | refinedweb | 197 | 64.51 |
NAME
OPENSSL_VERSION_NUMBER, OPENSSL_VERSION_TEXT, SSLeay, SSLeay_version - get OpenSSL version number
SYNOPSIS
#include <openssl/opensslv.h> #define OPENSSL_VERSION_NUMBER 0xnnnnnnnnnL #define OPENSSL_VERSION_TEXT "OpenSSL x.y.z xx XXX xxxx" #include <openssl/crypto.h> long SSLeay(void); const char *SSLeay_version(int t);
DESCRIPTION
OPENSSL_VERSION_NUMBER is a numeric release version identifier:
M.
OPENSSL_VERSION_TEXT is the text variant of the version number and the release date. For example, "OpenSSL 1.0.1a 15 Oct 2015".
SSLeay() returns this number. The return value can be compared to the macro to make sure that the correct version of the library has been loaded, especially when using DLLs on Windows systems." otherwise.
-.
RETURN VALUE
The version number.
SEE ALSO
HISTORY
SSLeay() and SSLEAY_VERSION_NUMBER are available in all versions of SSLeay and OpenSSL. OPENSSL_VERSION_NUMBER is available in all versions of OpenSSL. SSLEAY_DIR was added in OpenSSL 0.9.7. | https://www.openssl.org/docs/man1.0.2/man3/OPENSSL_VERSION_TEXT.html | CC-MAIN-2022-33 | refinedweb | 139 | 61.53 |
Ruby Recap (What you're going to need) Methods require vs include/extend require works similarly to 'using' in C# (usage) No explict return
Can use ? in ! method names
Can redefine later Blocks Can sometimes be used like methods, really a special way to call a kind of method or... include & extend is kind of like inlining code Modules Classes Can be used like C# abstract classes, also as a type of namespace Ruby modules are often 'mixed-in' to classes. But first we'll need to understand classes... Cucumber who knows why it's called this??? What's the point? Communication Thinking/Reasoning Automation Specification It is a bridge between non-technical domain experts (or at least those who are responsible for driving the project) "Eh? What do you mean after you press the 'next' button, I thought that would happen before anything else..." "No, no, let's change this to say..." "yes, that's fine but what if..." Provides a basis for discussion Plain English (or rather natural language) If your domain experts can't read it it is wrong! Top down approach (test driven) Features should keep you focused on what the point is Scenarios show the specifics QA, or even domain experts, may add new scenarios or suggest new features. (Normally it will be collaborative with QA and Dev doing the majority of work. However it does happen that interested domain experts are able to contribute autonomously.) Everyone can be more confident of specifications (This will be even more the case when we can give the business a general and easy-to-use method of viewing the features and scenarios. There are some interesting web-apps for just this. Also Jira may be an option.) Also doubles as documentation Regression Early warning We can get to the point where parts of the site are fully automated we will have higher confidence that our changes haven't screwed up something. May pave the way for continuous deployment Better to know on Day 2 that there's a problem caused by your changes you did this morning. ... rather than after dev complete Anatomy of a feature features Scenarios Steps Gherkin (the technical name for the feature file grammar) Tags, useful for organising/running (Although a bit scary for non-technical users.) Description (optional) Has 3 parts:
WHY (In order/So that)
WHO (As a ...)
WHAT (I need/I want) (Note, first person) Describes at the level of a story (this is a general rule of thumb.) Should not attempt to explain all the details, try to keep it short and sweet. If you can't reduce it to a couple of lines consider whether you're looking at more than one feature/story. Can be structured English Or unstructured Unstructured. Less common for us, but can be a simple paragraph or two of text. This can be good for describing more complex elements e.g., an algorthim. Keep in mind though this is a feature: a conceptually related unit 'thing'. Beware of using unstructured text instead of splitting into two or more features. You can reasonably have "In order I can book a table at my preferred time" in another feature file. Perhaps as part of the search. Similarly "I need to pick one of the offered time slots" could form the action of another feature, e.g. selecting an order.
A structured english style feature has an identity according to it's mix of why/who/what.
A feature file should be short. Don't try and cram everything in But what about the details? A scenario is a concrete list of steps which demonstrate the functionality desired. Typically there will be a 'Happy Path' scenario and a number of 'Alternate Paths'. All features have at minimum have a line that starts 'feature:' and continues with a title The feature name should be short and snappy. Due to the way we structure directories the context should be obvious (but don't treat it as such) If features are the why/who/what, scenarios are the where/how. Nobody wants to fill in forms no one normal anyway Ruby, annoying in some ways not to be using something like spec flow but... It has the advantage of being completely agnostic as to the technology implmeneting it. Tempting short-cuts don't exist, which is good because often these end up being a factor in our thinking (oh but then it would be hard to do such and such testing... no, because x relies on this 'hack' thing.. etc.) Also, less convincingly, some say you should always test in a more 'powerful' language. Finally Cucumber was built in Ruby to start with it has good support from Capybara and friends, and it's more friendly, we hope, to our tech literate QA team. And so, of course, I must go in search of this useless factoid, luckly the RSpec book can shed some light on the matter: In the spring of 2008, Aslak Hellesøy set out to rewrite RSpec’s Story Runner with a real grammar defined with Nathan Sobo’s Treetop library. Aslak dubbed it Cucumber at the suggestion of his fiancée, Patricia Carrier, thinking it would be a short-lived working title until it was merged back into RSpec. Little did either of them know that Cucumber would develop a life of its own. How we roll Me, not so long ago. Bad me! What's wrong with it? As a potential diner. So that's who I am, someone by definition looking to dine. (We're particularly interested in these types of people.)
I know want to eat, and when I want to eat it. I don't really care how I do that. Also, I don't really know what a timeslot is. Don't worry if it takes you time to get a feature or scenario right. You're trying to get an insight into what it is the business is aiming at. Sometimes this is by no means easy. Revise, refactor, revisit.
It's a poem, not an essay. A quick aside... Step back, why am I (the potential diner) even on this page? I came here via a search of some kind (internal or search engine) and I'm therefore, presumably, at least open to the idea of booking this restaurant. So Now I want to see if it's even possible to make the kind of booking I want: tomorrow, for lunch with two clients. A better feature: Generally name your feature file in as feature_name.feature Where the rubber meets the road ToW Background Tables Scenario Outlines A rule I try and follow in my scenarios is whether I could read the scenario as-is over the phone to the person noted in the feature? "Everything should be made as simple as possible, but no simpler" -- Albert Einstein Much like features a scenario must start with 'scenario:' followed by a title Given The setup needed for the test
Avoid unecessary cluttering
Ands and Buts
Usually needed Actually the example given could be improved. Whilst the logged in or not is relevant to the example "WA Test Venue" is somewhat questionable.
Perhaps this should be hidden away in a 'background' section (covered in a moment) or else renamed to something like '"Restaurant with availability".
Discuss. } When The action, the thing the user does to set everything in motion.
Try to keep it down to one or two at most per scenario
Not always needed Then The expectation of the scenario
As with Given/When statements you can use as many Ands/Buts wanted.
All scenarios should have at least a Then statement (otherwise what's the point?) More advanced syntax... Quite often the setup for each scenario in a feature is necessaryly similar... And whilst important from a context point of view it is distracting noise. So for example: becomes... Quoted strings Sometimes you'll need to repeat the same scenario structure over and over again. boring! Instead fo all this repetition we would like to extract the common elements and just note the differences between each one. { { template section examples section Occasionally it would be clearer to list out some part of the scenario without the fluff of a fully formed sentence. ... in our code-base examples are scarce, so here's an example from the interwebs: source: headings content More of a convention, although it may have consequnce for your step definitions... Only one content line is used in this example, but it should be clear how more than one can be added. ( I am generally wary of when I see tables being used. Sometimes they can be a great solution, but they are also open to misuse. Bottom line: does it make it simpler to understand the scenario? If yes, but still complex perhaps your scenario is trying to do too much and should be split into smaller more focused scenarios. ) WARNING Tags As with features, scenarios may be decorated with tags So, for example: Other possibilities may include: It is at this point the human friendly text is connected to something the computer can understand.
In our case via the Ruby languauge. Steps Each of the Given, When, Then, And and But lines are called 'steps' (Ruby code) Each step is matched to a 'step definition' (We'll come to exactly how this happens later on.) This then uses a Ruby library, called Capybara, connected to a utility call Selenium which is used to drive the web browser Firefox 3.6, but it should be possible to run against, say, Chrome. After which the success or not is shown Lather, rince, repeat. To know more we're going to have to recall some Ruby.
Cucumber and Ruby
Acceptance testing
byTweet
Philip Coxon 12 July 2011
Please log in to add your comment. | https://prezi.com/mdzph4o5mwkg/cucumber-and-ruby/ | CC-MAIN-2017-26 | refinedweb | 1,645 | 71.44 |
One.
Initially, I started out modifying the out-of-the-box Approval InfoPath form (Review-RoutingInit.xsn) and was able to successfully populate the Approvers field with hardcoded data but I then realized that I didn’t know what Item the workflow had been started on, which meant I couldn’t figure out who the Approver was for the specific item that the workflow had been started. So, I scrapped that idea and decided to create a new InfoPath Workflow initiation page (this is the page that loads the InfoPath Forms on initiation).
After using Lutz Roeder’s . NET Reflector to analyze the IniWrkflIPPage.aspx page, I was able to determine that if I wanted to change the AssociationData before it was populated into the InfoPath Form Control, I needed to modify the property m_formData before the page finished its databinding.
I then went on to modify the form data using metadata from the item that initiated the workflow. Because I wanted to inherit my custom InfoPath initiation form from IniWrkflIPPage.aspx, I realized that I couldn’t change the code in the OnLoad event, but instead needed to change it on the DataBind event.
As it turned out, apparently some of the global variables in the IniWrkflIPPage.aspx don’t “port” very well over to my custom page, so I ended up faking it a bit. There is probably a better way to do this but at this point I didn’t care J
With the code above precompiled into a DLL, all I needed to was modify two lines of my copied IniWrkflIPPage.aspx and that was to add my assembly and to change the page inherits to our new codebehind page.
<%@ Assembly Name="TeamEli.Sharepoint.Workflow.ApprovalWorkflow, Version=1.0.0.0, Culture=neutral, PublicKeyToken=<<PUBLICKEYTOKEN>>"%><%@ Page Language="C#" Inherits="TeamEli.Sharepoint.Workflow.ApprovalWorkflow.ApprovalIniWrkflIP" MasterPageFile="~/_layouts/application.master" EnableSessionState="true" AutoEventWireup="false" %>
All that was left was to create a new Feature that calls our new initiation page. And volia!
Hopefully some of this made sense. If not, let me know.
Eli
Pingback from Sharepoint link love 06-21-2007 at Virtual Generations
I can't even find or activate the "out of the box approval workflow" it doesn't exist on my damn system. so sick of this junk that doesn't work and documentation that doesn't match the crap they put out.
Henry,
Sounds like you need to sit back and take a deep breath. :) Anyways, can you explain what you are trying to do so that I can help you out?
Thanks, Eli
Eli,
Could you please tell me where can I find the out-of-the-box Approval InfoPath forms??
vuong,
Some of the Infopath formsare actually located in the Feature folder called ReviewWorkflows and then in the Forms folder. Here is location on my machine...
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\FEATURES\ReviewWorkflows\Forms
Hope this is what you are looking for and that I am not too late ;)
Eli-
Thanks for shedding some light on these mysterious "out of the box" aspx forms that come with MOSS! I was beginning to think it was a forbidden subject, because no-one to date seems to have said much about them.
I am building a custom ASSOCIATION form for a workflow created in WSS 3.0 (no MOSS) with Visual Studio 2005. My workflow forms were created with InfoPath 2007, are compiled into my workflow and have been published to Office Forms Server 2007.
I've modified workflow.xml file to use my custom aspx pages, have the InfoPath forms hosted in an XmlFormView control and everything deployed, but when I try to associate a workflow with my libraries I get an "unknown error" from SharePoint. I'm thinking either it's a syntax issue or I'm missing some code in my pages.
So my question: Do you know if anyone has run the Reflector and documented what these pages are supposed to contain? That would be helpful for those of us who are doing this from scratch and don't have the MOSS pages as a starting point.
Thanks in advance
I just found the reflector on Lutz's website and installed it - wow! what a handy tool!
My question is this: How did you use it to analyze aspx pages? Are these pages compiled into a dll somewhere?
Tx
The best way to do this is to search for the “inherits” attribute within the aspx page. You can find this attribute within the “Page” tag near the top of the aspx page.
It looks something like this.
<%@ Page Language="C#" Inherits="Microsoft.SharePoint.ApplicationPages.SettingsPage" MasterPageFile="~/_layouts/application.master" EnableViewState="false" EnableViewStateMac="false" %>
The “inherits” attribute will tell you the namespace and class that this application (aspx) page uses. Once you have this, you can defer what the dll is being used. In the example above, it is Microsoft.SharePoint.ApplicationPages. Therefore, you can open the Microsoft.SharePoint.ApplicationPages dll with Reflector and then navigate until you find a class that matches the inherits tag, in our example, SettingsPage.
HTH.
Hi Eli,
I am not able to understand where can i find the onload and DataBind methods.
Frankly speaking, i am not able to get how to follow the specified process.
Can you please explain more details?
Thanks,
Sonu
Is there any way to customize the Out of Box workflow where we can check if the modifier is same as approver? If they are then the workflow gives error that modifier cannot be same as Approver.
It is such a nice article and i can able to fill the initiation form at run time.
But i have one query...
Can we prepopulate Association form at run time.
In my case, i'll be having a workflow which will be configured in two sites. In the approver field i am filling up the name of a site group, which is different in both the sites.
Is there any way to prefill the approvers field in association form with the group name depending on the site.
Hi, Good Works!!!
I implemeted the above in my portal. In my case, i am using the existing sharepoint approval. So i am retrieving the workflow's association data, modifying the approvers and starting the workflow during the check-in. During the checkin it goes to the workflow page, but none of my approver names were displayed it was blank. but if you see the list item, workflow was initiated and approver name also present there... I dont know how to resolve this problem as well as while starting a workflow i am receiving this exeception: Exception from HRESULT: 0x8102009B ---> System.Runtime.InteropServices.COMException (0x8102009B): Exception from HRESULT: 0x8102009B
Any words will be really helpful!!!
Hi Vimal,
Can you email me a sample of your code, what you changed against what I posted? I can take a look to see if anything stands out.
powerlaptop2001 at yahoo dot com
Take out _ in the above address ;)
Exception from HRESULT: 0x8102009B ---> System.Runtime.InteropServices.COMException (0x8102009B): Exception from HRESULT: 0x8102009B
I get this error when i assign the data to a running already running. Cancel the workflow and try again.
Hope it helps
Lui
Hello, I am new to Sharepoint Design, but have developed part-time before. I am attempting to add some fields to the canned "Helpdesk.wsp" workflow process, which other than a couple of missing fields, I am very happy with it. First, I am having trouble finding the workflows I wish to modify. Second, once located, I need to know the simplest way to add the fields we desire. Third, I need to save and publish without losing the original flow as designed, in case we need to move forward with that instead. Thanks!
Just a note, you can just copy the .aspx and copy your "DataBind()" method into a "server-side" script.
You don't even need to change the inheritance.
That way you just have the .aspx to deploy and your make sure your [workflow.xml] the [InstantiationUrl] to point to your new page.
Hey Eli,
Wondeful post! I have a question that relates to what you did above: Is it possible to use the Reflector to mimic the Approval workflow and customize the approval buttons from; Approve, Reject, Cancel to Yes, No, True, False, and several other predefined buttons that all set to complete the workflow on click.
I want to use the built in association form with document approval workflow in sharepoint with my custom workflow. how can i do this? i have to design the association form same like sharepoint and code it or i can use that built in associatioin form by any other way, i am sturuggling with this porblem from last 6 days. thanx in advance please help me | http://www.sharepointblogs.com/teameli/archive/2007/06/20/modifying-the-workflow-association-data-in-sharepoint-2007-pre-initiation.aspx | crawl-002 | refinedweb | 1,482 | 64.1 |
Site navigation:
See NineML_import_test.py.
PyDSTool now directly supports the importing of NineML model specifications via the Python API. Details of installing that software can be found in the link. The NineML toolbox is currently in development. Only "flat" models are currently importable, but support for the full feature set is being actively developed in collaboration with the authors of NineML. The interface is extremely easy to use. Just build a model in NineML, and export it as a "component" using the python interface. In the examples below, the simple single neuron models are built directly using the python-NineML API, but they could have been loaded first from NineML files. A warning will be generated about not providing initial conditions at the time of definition.
from PyDSTool import * from PyDSTool.Toolbox.NineML import * c = get_HH_component() # Convert to PyDSTool.ModelSpec and create NonHybridModel object # Provide extra parameter Isyn which is missing from component definition # in absence of any synaptic inputs coupled to the model membrane HHmodel = get_nineml_model(c, 'HH_9ML', extra_args=[Par('Isyn')]) HHmodel.set(pars={'C': 1.0, 'Isyn': 20.0, 'celsius': 20.0, 'ek': -90, 'el': -65, 'ena': 80, 'gkbar': 30.0, 'gl': 0.3, 'gnabar': 130.0, 'theta': -40.0}, ics={'V': -70, 'm': 0.1, 'n': 0, 'h': 0.9}, tdata=[0,15]) HHmodel.compute('test', force=True) pts = HHmodel.sample('test') plt.plot(pts['t'], pts['V'],'k') plt.title('Hodgkin-Huxley membrane potential') ev_info = pts.labels.by_label['Event:spikeoutput'] for ev_ix, ev_tdata in ev_info.items(): plt.plot(ev_tdata['t'], pts[ev_ix]['V'], 'ko') plt.xlabel('t') plt.ylabel('V') | http://www.ni.gsu.edu/~rclewley/PyDSTool/Tutorial/Tutorial_NineML.html | CC-MAIN-2017-09 | refinedweb | 264 | 54.69 |
Enables the Editor to handle an event in the Scene view.
In the OnSceneGUI you can do for example mesh editing, terrain
painting or advanced gizmos. If
Event.current.Use() is called the event will be "eaten"
by the editor and not be used by the Scene view itself.
In the following two scripts OnSceneGUI is used to draw lines between game objects. The first script shows how OnSceneGUI is used. In this script a game object is used as a parent. The position of the parent is obtained and then lines are draw from this to game objects stored in an array. The Handles.DrawLine function is used for this. The documentation for Handles.DrawLine has a very similar example.
using UnityEngine; using UnityEditor;
[CustomEditor( typeof( DrawLine ) )] public class DrawLineEditor : Editor { // draw lines between a chosen game object // and a selection of added game objects
void OnSceneGUI() { // get the chosen game object DrawLine t = target as DrawLine;
if( t == null || t.GameObjects == null ) return;
// grab the center of the parent Vector3 center = t.transform.position;
// iterate over game objects added to the array... for( int i = 0; i < t.GameObjects.Length; i++ ) { // ... and draw a line between them if( t.GameObjects[i] != null ) Handles.DrawLine( center, t.GameObjects[i].transform.position ); } } }
This script stores the array of game objects which will have a line drawn to them. This regular script is simply attached to a game object which is considered to be the starting point for all lines.
using UnityEngine;
[ExecuteInEditMode] public class DrawLine : MonoBehaviour { // an array of game objects which will have a // line drawn to in the Scene editor public GameObject[] GameObjects; } | https://docs.unity3d.com/ru/2019.1/ScriptReference/Editor.OnSceneGUI.html | CC-MAIN-2022-33 | refinedweb | 275 | 66.13 |
Interaction plays a key role in shaping the experience a user has on an application. Animations help define these interactions since the user's eyes tend to pay attention to moving objects. These catchy and moving elements tell a story that helps the application differentiate from competitors and bring a better user experience.
Creating animations can be daunting, especially programming and handling orchestrations (how these coordinate between each other). Thankfully, amazing people have created abstractions in libraries that allow the developer to create seamless, hardware-accelerated animations efficiently.
In this post, I will give an introduction to Framer Motion and create simple animations with it. We'll be learning about motion components, orchestration, dragging, and automatic animations.
React Animation Libraries
In React, we have two main animation libraries: React Spring and Framer motion. I like both of them, but I believe each one has a use case.
React Spring is a spring-physics based animation library. These animations emulate real spring physics for smooth animations. It is really powerful and flexible. Almost all properties of HTML tags can be fully animated with React Spring. This is especially important for complex and SVG animations, however, Its main disadvantage is its high learning curve.
Framer Motion is a motion library. It is easy to learn and powerful with orchestrations. Contrary to React Spring, it has more types of animations: spring, tween, and inertia. Tween represent duration based animations like CSS, and inertia decelerates a value based on its initial velocity, usually used to implement inertial scrolling.
Framer Motion is perfect for handling animations on 99% of sites. Its main disadvantage is its lack of documentation and some properties won't work for SVG animations.
Choosing between these libraries depends greatly on what you are building and how much you are willing to devote to learning animations. React Spring can do all that Framer Motion does with more flexibility, but it is harder to read and understand. I recommend it for custom, complex animations especially for SVG and 3D (Three.js).
For most websites, Framer Motion is better since it can handle most common cases and its learning curve is really low compared to React Spring. Also, its way of handling animations is more intuitive and declarative. This is why we'll focus on this library and learn about animations with it. The fundamentals of Framer Motion will be transferable to React Spring, however its syntax will be more abstract.
How It Works: Motion components
Framer motion core API is the
motion component. There's a
motion component for every HTML and SVG element. They work exactly the same as their HTML counterparts but have extra props that declaratively allow adding animations and gestures.
Think of
motion component as a big JavaScript object that can be used to access all HTML elements. Here are some ways one would call a
motion component:
<motion.div /> <motion.span /> <motion.h1 /> <motion.svg /> ...
As said before, they allow for extra props. Some of the most used are:
initialdefines the initial state of an element.
styledefines style properties just like normal React elements, but any change in the values through motion values (values that track the state and the velocity of the component) will be animated.
animatedefines the animation on the component mount. If its values are different from
styleor
initial, it will automatically animate these values. To disable mount animations
initialhas to be set to
false.
exitdefines the animation when the component unmounts. This works only when the component is a child of the
<AnimatePresence />component.
transitionallows us to change animation properties. Here one can modify the duration, easing, type of animation (spring, tween, and inertia), duration, and many other properties.
variantsallows orchestrating animations between components.
Now that we know the basic props that
motion can contain and how to declare them, we can proceed to create a simple animation.
Mount Animations
Let's say we want to create an element that on mount will fade in down. We would use the
initial and
animate prop.
Inside the
initial property, we'll be declaring where the component should be located before it mounts. We'll be adding an
opacity: 0 and
y: -50. This means the component initially will be hidden and will be 50 pixels up from its location.
In the
animate prop, we have to declare how the component should look when it is mounted or shown to the user. We want it to be visible and located on its initial position, so we'll add an
opacity: 1 and
y: 0.
Framer Motion will automatically detect that the
initial prop has a different value from the
animate, and animate any difference in properties.
Our snippet will look like this:
import { motion } from "framer-motion" <motion.div initial={{ opacity: 0, y: -50 }} animate={{ opacity: 1, y: 0 }} > Hello World! </motion.div>
This will create the following animation:
Congratulations on creating your first animation with Framer Motion!
💡 You may have noticed that styles are missing from the snippets above. Some of the snippets will lack the styles in order to focus on Framer Motion's functionality.
📕 All animations in this post will have their own Storybook. Here is the link of the latter.
Unmount Animations
Unmounting or exit animations are crucial when creating dynamic UIs, especially when deleting an item or handling page transitions.
To handle exit animations in Framer Motions, the first step is to wrap the element or elements in an
<AnimatePresence/>. This has to be done because:
- There is no lifecycle method that communicates when a component is going to be unmounted
- There is no way to defer unmounting until an animation is complete.
Animate presence handles all this automatically for us.
Once the elements are wrapped, they must be given an
exit prop specifying their new state. Just like
animate detects a difference in values in
initial,
exit will detect the changes in
animate and animate them accordingly.
Let's put this into practice! If we take the previous component and were to add an exit animation. We want it to exit with the same properties as it did in initial
import { motion } from "framer-motion" <motion.div exit={{ opacity: 0, y: -50 }} initial={{ opacity: 0, y: -50 }} animate={{ opacity: 1, y: 0 }} > Hello World! </motion.div>
Now, let's add a
<AnimatePresence/> so it can detect when our component unmounts:
import { motion } from "framer-motion" <AnimatePresence> <motion.div exit={{ opacity: 0, y: -50 }} initial={{ opacity: 0, y: -50 }} animate={{ opacity: 1, y: 0 }} > Hello World! </motion.div> </AnimatePresence>
Let's see what happens when the component unmounts:
Orchestration
One of Framer Motion's strong suits is its ability to orchestrate different elements through variants. Variants are target objects for simple, single-component animations. These can propagate animations through the DOM, and through this allow orchestration of elements.
Variants are passed into
motion components through the
variants prop. They normally will look like this:
const variants = { visible: { opacity: 0, y: -50 }, hidden: { opacity: 1, y: 0 }, } <motion.div initial="hidden" animate="visible" variants={variants} />
These will create the same animation as we did above. You may notice we passed to
initial and
animate a string. This is strictly used for variants. It tells what keys Framer Motion should look for inside the variants object. For the
initial, it will look for 'hidden' and for
animate 'visible'.
The benefit of using this syntax is that when the motion component has children, changes in the variant will flow down through the component hierarchy. It will continue to flow down until a child component has its own
animate property.
Let's put this into practice! This time we will create a staggering list. Like this:
In the image, each item has an increasing delay between each other's entrance. The first one will enter in 0 seconds, the second in 0.1 seconds, the third in 0.2, and it will keep increasing by 0.1.
To achieve this through variants, first, let's create a variants object where we'll store all possible states and transition options:
const variants = { container: { }, card: { } };
variants.container and
variants.card represent each
motion component we'll have.
Let's create the animations for the cards. We see that the cards go from left to right while fading in. This means we have to update its
x position and
opacity.
As aforementioned, variants can have different keys for their animation states, however, we will leave it as
initial and
animate to indicate before mount and after mount, respectively.
On
initial, our component will be 50 pixels to the left and its opacity will be 0.
On
animate, our component will be 0 pixels to the left and its opacity will be 1.
Like this:
const variants = { container: { }, card: { initial: { opacity: 0, x: -50 }, animate: { opacity: 1, x: 0 } } };
Next, we have to add the stagger effect to each of these cards. To achieve this we have to add the
container.transition property which allows us to update the behavior of our animation. Inside the property, we'll add a
staggerChildren property that defines an incremental delay between the animation of the children.
const variants = { container: { animate: { transition: { staggerChildren: 0.1 } } }, card: { initial: { opacity: 0, x: -50 }, animate: { opacity: 1, x: 0 } } };
Now, if we hook this variant to the
motion components:
import { motion } from "framer-motion"; const variants = { container: { animate: { transition: { staggerChildren: 0.1 } } }, card: { initial: { opacity: 0, x: -50 }, animate: { opacity: 1, x: 0 } } }; const StaggeredList = () => { return ( <motion.div initial="initial" animate="animate" variants={variants.container} > {new Array(5).fill("").map(() => { return <Card />; })} </motion.div> ); }; const Card = () => ( <motion.div variants={variants.card} > Hello World! </motion.div> );
With this, our animation is complete and sleek staggered list ready!
Dragging
Dragging is a feature that can be daunting to implement in an app. Thankfully, Framer Motion makes it a lot easier to implement its logic because of its declarative nature. In this post, I will give a simple, general introduction to it. However, in a future tutorial, I may explain with more details about how to create something more complex like a slide to delete.
Making an element draggable is extremely simple: add a
drag prop to a
motion component. Take for example the following:
import { motion } from "framer-motion"; <motion.div drag> Hello World! </motion.div>
Adding the
drag prop will make it draggable in the x-axis and y-axis. It should be noted that you can restrict the movement to a single axis by providing the desired axis to
drag.
There is a problem with just setting the
drag property. It is not bound to any area or container so it can move outside the screen like this:
To set constraints we give the
dragContraints an object with our desired constraints for every direction:
top,
left,
right, and
bottom. Take for example:
import { motion } from "framer-motion"; <motion.div drag dragConstraints={{ top: -50, left: -50, right: 50, bottom: 50 }} > Hello World! </motion.div>
These constraints allow the element to move 50 pixels maximum in any direction. If we try to drag it, for example, 51 pixels to the top, it will be stopped and bounced. Like this:
It is as there is an invisible wall with the form of a square that won't allow the component to move further.
Layout Property
The
layout prop is a powerful feature in Framer Motion. It allows for components to animate automatically between layouts. It will detect changes to the style of an element and animate it. This has a myriad of use cases: reordering of lists, creating switches, and many more.
Let's use this immediately! We'll build a switch. First, let's create our initial markup
import { motion } from "framer-motion"; const Switch = () => { return ( <div className={`flex w-24 p-1 bg-gray-400 bg-opacity-50 rounded-full cursor-pointer`} onClick={toggleSwitch} > {/* Switch knob */} <motion.div className="w-6 h-6 p-6 bg-white rounded-full shadow-md" layout ></motion.div> </div> ); };
Now, let's add our logic:
import { motion } from "framer-motion"; const Switch = () => { const [isOn, setIsOn] = React.useState(false); const toggleSwitch = () => setIsOn(!isOn); return ( <div onClick={toggleSwitch}> {/* Switch knob */} <motion.div layout ></motion.div> </div> ); };
You may have noticed that only our knob has the
layout prop. This prop is required on only the elements that we wish to be animated.
We want the knob to move from one side to the other. We could achieve this by changing the container flex justification. When the switch is on then the layout will have
justify-content: flex-end. Framer Motion will notice the knob's change of position and will animate its position accordingly.
Let's add this to our code: ></motion.div> </div> ); };
I added some other styles so it can resemble the look of a switch. Anyway, here is the result:
Great! It is amazing how Framer Motion can do this automatically without having to deal with extra controls. Anyhow, it looks a little bland compared to what we are used to seeing on apps like Settings. We can fix this pretty quickly by adding a
transition prop. transition={{ type: "spring", stiffness: 500, damping: 30, }} ></motion.div> </div> ); };
We define a spring-type animation because we want a bouncy feel.
The
stiffness defines how sudden the movement of the knob will look.
And,
damping defines the strength of the opposing force similar to friction. This means how fast it will stop moving.
These together create the following effect:
Now our switch looks more alive!
Conclusion
Creating animations can be daunting, especially when many libraries have complex jargon. Thankfully, Framer Motion allows developers to create seamless animations with its declarative an intuitive API.
This post was meant as an introduction to the fundamentals of Framer Motion. In future posts, I will create complex animations like swipe to expand and delete, drawers, shared layout, and many more. Please let me know in the comments if you have any suggestions as to what you want to see animated!
It looks awesome! I need to test this out!
Thanks for your post :D | https://practicaldev-herokuapp-com.global.ssl.fastly.net/joserfelix/getting-started-with-react-animations-308a | CC-MAIN-2021-04 | refinedweb | 2,348 | 57.67 |
Using the DS18B20 Temperature Sensor with a WeMos D1 Mini (ESP8266)
In this blog post I talk about the additional steps needed to use the DS18B20 onewire temperature sensor with a WeMos D1 Mini (ESP8266) using the Arduino IDE.
Important differences compared to using the DS18B20 on an Arduino
There is one major difference to bear in mind when using the DS18B20 WS18B20 properly I recommend having a read.
Wiring it up to a WeMos D1 Mini
Here I am connecting the WS18B20 sensor to a WeMos D1 mini. To more easily connect the sensor I have connected the 3.3 volt and GND lines to the breadboards + and – lines respectively.
The pins on the WS18B20 temperature sensor are, from left to right, GND, Data, and VCC.
It is important to note that the WeMos’s digital pins can only accept up to 3.3 volts maximum on their inputs. This means that the WS18B20 sensors VCC pin must be connected to the 3.3 volts and not the 5 volt line like when using the Arduino.
The data pin is connected to D2 on the WeMos. This is also connected to a 4.7k resistor between the data pin and the 3.3 volt line on the breadboard. This pull-up resistor ensures that the line is pulled up when floating.
Programming the WeMos to use the WS18B20 sensor
Since the WS18B20 uses the onewire protocol I can use the onewire library coupled with the Dallas Temperature library. This will let me address my WS18B20 temperature sensor and read out the temperature in Celcius.
#include <OneWire.h> #include <DallasTemperature.h> #define ONE_WIRE_PIN D2 OneWire oneWire(ONE_WIRE_PIN); DallasTemperature sensors(&oneWire); void setup() { Serial.begin(115200); } void loop() { sensors.requestTemperatures(); Serial.println(sensors.getTempCByIndex(0)); delay(1000); }
As noted above I am using the constant
D2 instead of
2 to refer to digital pin 2 as the WeMos pin numbering is different from the Arduino.
Since I only have one onewire temperature sensor on pin
D2 I call the temperature function asking for the first device (numbered 0) when calling
sensors.getTempCByIndex(0).
Summary
The WS18B20 is a useful temperature sensor that uses the onewire protocol. This can be very useful to combine multiple sensors on the same digital pin. This is more important on the smaller WeMos and ESP8266 devices with limited pins. In this case, the Arduino onewire and Dallas Temperature library works the same as when using the Arduino so no ESP8266 specific code is needed.
For a full review of the WS18B20 temperature sensor have a read of my previous post.
Hey superrb website! Does running a blog such as tthis take
a large amount oof work? I have very little knowledge of coding but I was
hoping tto start my own blog soon. Anyway, if you
have any recommendations or techniques for new blog owners please share.
I know thi is off subject nevertheless I simply nseded to ask.
Appreciate it! | https://chewett.co.uk/blog/1412/using-the-ds18b20-temperature-sensor-with-a-wemos-d1-mini-esp8266/ | CC-MAIN-2020-40 | refinedweb | 495 | 64.91 |
My name is Kathy Kam and I am the newest addition to the Common Language Runtime (CLR) Program Management (PM) team. Like another PM on my team, JoelPob, I also grew up in the "Land Down Under". I left Sydney to pursue a degree in Computer Engineering and Mathematics at the University of Michigan - Ann Arbor. Upon graduation, I joined Microsoft as a developer for Microsoft Office Outlook. Four years later, after shipping Microsoft Office System 2003, a handful of Service Packs and working on Office 12 for two years, I decided to become a PM on the CLR team and here I am, writing my first post!
This blog will be a record of my insights to the .NET world. In the computing community, the first thing any developer writes is a "Hello World" program. Since this is a blog for all the computer geeks in us. Here it is, "Hello World" Reflection style:
using System;
using System.Reflection;
namespace HelloWorld
{
class Program
{
static void Main(string[] args)
{
foreach (FieldInfo fi in typeof(HelloObj).GetFields())
Console.Write(fi.Name + " ");
}
}
class HelloObj
{
// My output
public string Hello;
public int World;
public bool from;
public int[] Kathy;
public float Kam;
}
}
The output will be:
> Hello World from Kathy Kam
lol. That is one of the cleverest ways I’ve seen to do "Hello World".
Hi!
Just to be the wiseguy that I am, I have to point out that your code is broken. It depends on Type.GetFields() to return the fields in a particular order, but the order is not guaranteed.
Say hi to Joel for me 🙂
Hi Kathy,
The geek world welcomes you.
BTW, do you really need the public fields ? And the lower case in "from".. hum.. And "HelloObj" ? It is an object already ? 🙂 The FxCop team will ban this hello, no ?
Just kidding 🙂
Nice way to do a hello world Kathy,All the best at the CLR team
Hello! =)
Happy to see that you’ve started a blog, another one for my list and more information to gather 🙂
Marlun, Sweden
Hi Hugo,
Yeah, I was not following the Design Guidelines. My bad. I made "from" lower case so that it spells it out like a sentence correctly. Regarding "HelloObj"… old habits die hard.
Cheers,
Kathy
Hi Kathy,
you’re welcome. The first question that came to my mind when I was looking at your program is why ‘Kathy’ field is an array? Is there any special meaning in this?
Sorry if I’m missing something obvious 🙂
Regards,
Dmitry
Kathy, aren’t you heared about new Lambda-style programming? Here is more modern way to do things 😉
static void Main(string[] args)
{
List<FieldInfo> fields = new List<FieldInfo>(typeof(HelloObj).GetFields());
List<string> fieldNames = fields.ConvertAll<string>(
delegate(FieldInfo f) { return f.Name+" "; });
fieldNames.ForEach(Console.Write);
}
Or even shorter:
static void Main(string[] args)
{
new List<FieldInfo>(typeof(HelloObj).GetFields())
.ConvertAll<string>(delegate(FieldInfo f) { return f.Name+" "; })
.ForEach(Console.Write);
}
Hi Kathy,
Congrats on your new position. That was certainly a creative way to Hello the world.
By the way, since you just joined the team, the interview experience must be fresh in your mind. Can you blog about your PM interview experience in the CLR team?
Thanks
SN
Hello,
sorry, but how can one really get the order in which FieldInfoS are returned by Type.GetFields(), as <a href="">Jeroen Frijters</a> pointed? This is an interesting question and msdn keeps silent …
Thank you
Cool !
Could we force the field layout by:
[StructLayout(LayoutKind.Sequential)]
class HelloObj { … }
Or does StructLayout only have effect only when the object is actually marshaled to the unmanaged code? | https://blogs.msdn.microsoft.com/kathykam/2005/09/21/hello-world-reflection-style/ | CC-MAIN-2017-43 | refinedweb | 609 | 66.33 |
Thanks, it all works now. On 08/18/2015 12:53 PM, Thomas Caswell wrote: > Also, please use the new mailing list at matplotlib-users at python.org > <mailto:matplotlib-users at python.org> > > > > On Tue, Aug 18, 2015 at 12:53 PM Thomas Caswell <tcaswell at gmail.com > <mailto:tcaswell at gmail.com>> wrote: > > This is related to files from the previous implementation still > being around. Please make sure you have fully removed the old mpl > installation before installing the new one. Be aware that there > is some difference in the way pip/setuptools/distutils deal with > namespace packages so look for both `matplotlib` and > `mpl_toolkits` directories. > > Tom > > On Tue, Aug 18, 2015 at 12:49 PM Bob Dobalina <aspannaus at gmail.com > <mailto:aspannaus at gmail.com>> wrote: > > When trying to create a 3D axes, I receive this error: > > /usr/lib/pymodules/python2.7/mpl_toolkits/mplot3d/axes3d.pyc > in grid(self, > b, **kwargs) > 1254 if len(kwargs) : > 1255 b = True > -> 1256 self._draw_grid = maxes._string_to_bool(b) > 1257 > 1258 def ticklabel_format(self, **kwargs) : > > AttributeError: 'module' object has no attribute '_string_to_bool' > > I'm running matplotlib 1.4.3 on linux (ubuntu-based), and was > able to create > 3D axes until I updated last week. > > Thanks in advance. > > > > > -- > View this message in context: > > Sent from the matplotlib - users mailing list archive at > Nabble.com. > > ------------------------------------------------------------------------------ > _______________________________________________ > Matplotlib-users mailing list > Matplotlib-users at lists.sourceforge.net > <mailto:Matplotlib-users at lists.sourceforge.net> > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <> | https://mail.python.org/pipermail/matplotlib-users/2015-August/000051.html | CC-MAIN-2021-31 | refinedweb | 249 | 60.61 |
Scala: Repeated Method Parameters
Scala: Repeated Method Parameters
Let's see how Scala supports variable arguments and repeated method parameters and the conditions to consider when using them.
Join the DZone community and get the full member experience.Join For Free
How do you break a Monolith into Microservices at Scale? This ebook shows strategies and techniques for building scalable and resilient microservices.
Similar to Java, Scala also supports variable arguments or repeated method parameters. The concept is really useful in situations when you don't know how many parameters you need to pass to a method, or you have to pass an unlimited number of arguments to a method.
However, there are few conditions to using repeated method parameters in Scala
All the repeated parameters must be of the same type.
We can only have one argument as a repeated parameter in the method definition. We cannot declare 2 repeated parameters for a method.
Scala only allows the last parameter of the method call to be repeated.
To denote a repeated parameter, place an asterisk after the type of the parameter. For example, below is a sum method that would calculate the sum of all the numbers passed to the method.
def sum(args: Int*): Int = args.fold(0)(_+_)
You can call sum as
sum() or
sum(3,4) or
sum(1,3,4,5,7,8,9). Scala treats incoming parameters as arrays. However, if you try to pass an array to
sum(), Scala will throw a type mismatch error.
scala> sum(Array(1,2)) <console>:13: error: type mismatch; found : Array[Int] required: Int sum(Array(1,2))
In order to pass an array, we need to append the argument with a colon and an _* symbol.
scala> sum(Array(1,2): _*) res4: Int = 3
This notation will ask the compiler to pass each element of the array as a single argument. So array elements are passed one by one to
sum(), rather than all of it as a single argument.
Please refer to this video to understand the concept in more detail and to check out a few more examples. }} | https://dzone.com/articles/scala-repeated-method-parameters | CC-MAIN-2018-39 | refinedweb | 357 | 63.19 |
Post your Comment
Getting list of Local Interfaces on a machine
Getting list of Local Interfaces on a machine... to find out the
total no of list of local interfaces available on a machine. Here... the list
of local interfaces with the machine name and machine IP Address.
Here
Overview of Networking through JAVA,Getting list of Local Interfaces on a machine
Getting list of Local Interfaces on a machine... to find out the
total no of list of local interfaces available on a machine. Here... the list
of local interfaces with the machine name and machine IP Address.
Here
EJB Interfaces
;
}
4)Localhome Interface:-The local interfaces extend the following interfaces...
EJB Interfaces
Interface... interfaces. These are as follows
1)Remote interface:- Remote interface
Get Local Host Name
Get Local Host Name
... you in
understanding a code how to 'Get Local Host Name'. For this we have...,this class represents a Network
Interface made up of a name and a list of IP
Java Remote Interface
;
The Remote interface identifies
interfaces whose methods may be invoked remotely from a non-local virtual
machine. Any remote object must directly... of remote interfaces and can
extend other remote implementation classes
Identify correct and incorrect statements or examples about the client view of a session
bean's local and remote component interfaces.
the client view of a session
bean's local and remote component interfaces... the client view of a session
bean's local and remote component interfaces... local home interface.Test if the session object is identical with another
interfaces,exceptions,threads
interfaces,exceptions,threads SIR,IAM JAVA BEGINER,I WANT KNOW THE COMPLETE CONEPTS OF INTERFACES,EXCEPTIONS,THREADS
Interface... thread has its own local variables, program counter and lifetime. In single
interfaces
& interfaces.
An interface declaration introduces a new reference type whose members are classes, interfaces, constants and abstract methods... to directly implement one or more interfaces, meaning that any instance of the class
Java Virtual Machine
Java: Java Virtual Machine
After you read this section, you should be able... Machine.
The Java Virtual Machine
Most compilers translate from the source language (eg, C or Pascal)
into machine language for one specific type
Collection Interfaces
Collection Interfaces
...
of several interfaces, and classes that implement those interfaces, contained within... of objects.
Different interfaces
describe different types of functionalities
Java: Interfaces
Java: Interfaces
An interface is a list of methods that must be defined... does,
but abstract classes do allow static
method definitions, and interfaces... different interfaces. If a class doesn't define all
methods of the interfaces
Java Util Examples List
Java Util Examples List - Util Tutorials
... utility interfaces
and classes for easy manipulation of in-memory data. The java util... packages in the java
programming world and package provides many interfaces
Classes and Interfaces of the I/O Streams
Classes and Interfaces of the I/O Streams
...
stream in a machine format.
DataOutputStream
This class writes the primitive data types from the output
stream in machine format
Low port Scanner
Low port Scanner
In this section, you will learn how to get local port
number of the local machine. Here, we define the name of program LowPortScanner
Find winner of local election using ArrayList
Find winner of local election using ArrayList
Here is an example that allow the user to enter the last names of five
candidates in a local election...)
{
int total=0;
List<Candidate> list = new ArrayList<Candidate>
Jaipur Local Transport
Jaipur Local Transport
Tourist on a trip to Jaipur often want to know about Jaipur local transport as
it enable tourists to move from one place to other...
the Auto-rickshaw drivers have been given the fare chart, that offer a list
List control class
List control class Hi...
What Class does all list base controls...; Ans:
All list based control extend the ListBase class and implement..., IEffectTargetHost interfaces.
Thanks
washing machine
washing machine Create a washing machine class with methods as switchOn, acceptClothes, acceptDetergent, switchOff. acceptClothes accepts the noofClothes as argument & returns the noofClothes
public class
Local Language
Local Language Anybody help me.....
how to implement local language in my project
get files list - Ajax
get files list Please,friend
how to get files list with directories from ftp server or local files on web browser.
Thanks,
Tin Linn Soe Hi friend,
Index of Files
Index
Java interfaces
java interfaces
Identify the interfaces and methods a CMP entity bean must and must not implement.
Identify the interfaces and methods a CMP entity bean must and must... the interfaces and methods a CMP entity bean must and must not implement. ...;(...) method on the entity bean’s remote
home or local home interface
Marker interfaces in java
Marker interfaces in java how marker interfaces work
What are Callback interfaces?
What are Callback interfaces? Hi,
What are Callback interfaces?
thanks
List
List i do have one list object, i want to compare this list from database table and if match found i want to update the list
List
List getting values from a form and make a list of them and store them into database
Post your Comment | http://www.roseindia.net/discussion/24221-Getting-list-of-Local-Interfaces-on-a-machine-.html | CC-MAIN-2013-20 | refinedweb | 849 | 53.71 |
On 03/20/2012 10:36 PM, deadalnix wrote:
> Even the propagation of pure, @safe, nothrow and const that has been
> discussed recently can be done with that feature.
>
I'm sceptical. How would that work exactly??
Andrei
On Wednesday, 21 March 2012 at 16:21:21 UTC, Andrei Alexandrescu wrote:
>?
I'm not sure, you're understand of D's compiler-time structures is much better than mine. Serialization "attributes" are mostly used at runtime, so having mixing in a static enum *should* mean reflection upon the property at both runtime and compiletime.
On 2012-03-21 16:11, Andrei Alexandrescu wrote:
I think the liability here is that b needs to appear in two places, once
> in the declaration proper and then in the NonSerialized part. (A
> possible advantage is that sometimes it may be advantageous to keep all
> symbols with a specific attribute in one place.) A possibility would be
> to make the mixin expand to the field and the metadata at once.
Yes, but that just looks ugly:
class Foo
{
int a;
mixin NonSerialized!(int, "b");
}
That's why it's so nice with attributes.
> Did you mean
>
> static const __nonSerialized = ["b"];
>
> ?
Yes, sorry.
> In case there are several non-serialized variables, how do you avoid
> clashes between different definitions of __nonSerialized?
In my current implementation you are forced to only mixin one NonSerialized per type:
class Foo
{
int a;
int b;
mixin NonSerialized!(a, b);
}
Of course there are ways around that with various pros and cons.
--
/Jacob Carlborg
On 2012-03-21 16:20, F i L wrote:
> Andrei Alexandrescu wrote:
>> In case there are several non-serialized variables, how do you avoid
>> clashes between different definitions of __nonSerialized?
>
> struct A {
> int a, b;
> mixin NonSerialized!(a, b);
> }
>
> static const __nonSerialized = ["a", "b"];
>
Exactly.
--
/Jacob Carlborg
On 2012-03-21 16:26, F i L wrote:
> Also, if where meant how could you store multiple types, you could just
> use an Associative Array:
>
> struct A {
> int a;
> float b;
> mixin NonSerialized!(a, b);
> }
>
> static const __nonSerialized = ["int":"a", "int":"b"];
Only the name of the variables are necessary in my serialization library.
--
/Jacob Carlborg
Jacob Carlborg wrote:
> Only the name of the variables are necessary in my serialization library.
Wouldn't mixing in an enum be more useful? You could use it at compile time that way.
On Wednesday, 21 March 2012 at 16:02:22 UTC, Andrei Alexandrescu wrote:
> Ideally the above should work, and also mixing in several NonSerialized instances within the same type should also work.
Oh god, I feel like the spawn of Hacktan.
I'm taking the DSL identifiers to the max. Consider
the following:
Bottom line:
struct A {
int a;
int b;
mixin Note!(a, q{ "NonSerialized" });
mixin Note!(a, q{ "Awesome" });
mixin Note!(b, q{ "Filthy Hack" });
}
void main() {
pragma(msg, getNotes!(A.a));
}
$ dmd omg.d
["NotSerialized", "Awesome"]
How does it work?
What it does is for each note, it creates a dummy
enum.
The enum's name is a D expression, encoded as a
valid identifier. This expression is a ~= op here.
The struct looks like this:
struct A{
int a;
int b;
enum _attr_mixin_a_32_4c_NonSerialized;
enum _attr_mixin_a_32_4c_Awesome;
enum _attr_mixin_b_32_4c_Filthy_32_Hack;
}
getNotes looks for this pattern, decodes it,
and then mixes in the expression:
string[] notes;
if(identifier is the right item)
mixin("notes " ~ decoded_identifier);
return notes;
So, it embeds D code to rebuild the requested
data as the names of identifiers.
We run it every time we want to get it.
Note that everything I said in my long post still
applies here. Like I said before, we *can* make it
work, but it comes with a lot of baggage that hurts
maintainability and interop with third party code.
Remember, you have to add code to your library just
to *ignore* these attributes.
You can't just ignore them, no, you have to add special
code to skip them.
That's no good. This also has duplicated names and the
other problems mentioned before with overloading,
inheritance and more.
The compiler keeping a list of notes attached to the
declaration remains the only *right* way to do it. That
it is slightly prettier is an added benefit, but not the
main reason why we need it there.
On Wednesday, 21 March 2012 at 17:26:19 UTC, Adam D. Ruppe wrote:
> The compiler keeping a list of notes attached to the
> declaration remains the only *right* way to do it.
Another note on correctness btw, this thing is wrong
if in other modules.
mixin Note!(a, q{ NotSerialized() });
that string loses the exact type. But, let's
say we solved that, and uses the module name
or something.
But then, what if:
module cool;
import serialization.attributes;
struct cool {
int a;
mixin Note!(a, serialization.attributes.amazing);
}
==
// another module
import cool;
void main() {
getNotes!(cool.cool.a);
}
That won't compile. When it tries to mixin the note,
it will say undefinied identifier "amazing" because
the mixin is evaluated in another scope than the original
declaration.
So while module cool imported serilization.attributes,
module main or module notes (I'm not sure exactly where this
is mixed in by the time we're all said and done tbh but it
doesn't matter) has not.
Thus the mixin will fail.
I had this same problem when trying to do default arguments
in web.d by parsing stringof and mixing it in.
It works for built-in types like string and int, but
it doesn't work for user defined types, which are perfectly
valid function params (they work fine in the rest of web.d).
But the mixin scope is wrong so those types become undefined.
Again, we can get kinda close with these D tricks, but it
just cannot go all the way - and much of the interesting stuff
is behind that barrier.
The compiler can do it easily though, and get it right, enabling
us to do a lot more in the library down the line. | http://forum.dlang.org/thread/bccwycoexxykfgxvedix@forum.dlang.org?page=14 | CC-MAIN-2015-48 | refinedweb | 1,002 | 64.81 |
Quick-Start Tips
Look and feel
You can change colors for everything ReSharper brings into Visual Studio editor. Go toand find items starting with
ReSharper.
You can change ReSharper keyboard bindings for any action: go toand find items starting with
ReSharper.
In Visual Studio 2012 and later, you can use the Quick Launch feature to search and execute ReSharper commands.
While in the editor, press Alt+Enter and then start typing the name of a ReSharper command that you want to execute (more...).
Trying to learn ReSharper shortcuts? First, decide which of the two default shortcut schemes is more convenient to you. Then, use the selector in the right-upper corner of this page to switch shortcuts in help; or download and print a PDF version Visual Studio scheme or ReSharper 2.x / IntelliJ IDEA scheme.+W, (more...).
If you open parameter info pop-up (Ctrl+P), you can use Ctrl+P/ Ctrl+Shift+Alt+Space to jump to next/previous signature.
Enum completion will automatically insert the Enum type as the prefix. No need to spell it out!
Enums completion is CamelHumps-powered. Try typing
StringComparison c = oic.
With
String.Format, you can add a placeholder where the cursor is. Just hit Alt+Enter and choose Insert format argument (more...).
If a string literal is too long, hit Enter and ReSharper (more...).
Right-click on a file, project, solution folder or entire solution in the Solution Explorer and select Find Code Issues to see errors, warnings, and suggestions for the selected item (more...). ReSharper will not complain about anything until it meets the corresponding
// ReSharper restore All.
ReSharper's solution-wide analysis resolves visibility issues: you'll see if an internal member is used outside of its assembly and you'll never miss a single unused non-private member.
You can exclude files by masks from code analysis on the page of ReSharper options.
You can go to the next/previous code issue in the file by pressing F12 / Shift+F12.
To find all localizable strings in your solution, set Localizable=Yes and Localizable Inspector=Pessimistic for the relevant projects, then find any such string, which will be highlighted with curly underline. Press Alt+Enter on it and choose Inspection [name of inspection] | Find all issues of this type in scope. (more...).
Traversing code
You can press Ctrl+N to quickly locate a type, method, or basically everything, while Ctrl+Shift+N lets you locate files without other suggestions.
Place your caret on the
using(or
importif you work with VB.NET) directive and press Alt+F7. ReSharper will show where exactly this namespace is used (Finding Usages of a Symbol).
Forgot where you were editing just now? Go to last edit location with Ctrl+Shift+Backspace.
Want to locate where the current symbol is declared real fast? Press Ctrl+B or just right-click the symbol.
Go to containing declaration (Ctrl+[ ) can be used with Shift to select the whole declaration
When locating
CustomerServicesTestusing Ctrl+N or any other navigation command, you don't need to type the whole thing. Just use CamelHumps and type
cst.
Ctrl+U takes you to the base type and Ctrl+Alt+B takes you to inheritors of the current type.
Do you want to move to the next member in a class? Alt+Down will take you there; Alt+Up will bring you back (more...).
Search for anything (usages, implementations, code external to scope etc.) fetches to the Find Results window. Use it then to navigate between search results with F8/Shift+F8 (more...).
In source code, Shift+Alt+L selects the current file in the Solution Explorer; in decompiled sources, it opens the Assembly Explorer window focused on the current type (more...).
To explore the stack trace that is currently in your clipboard, just press Ctrl+Shift+E.
Start typing in a ReSharper tool window, and the content will narrow down to matching items. CamelHumps matching works there as well.
Use Go To File (Ctrl+Shift+N) to locate specific project in the Solution Explorer - just select a .csproj file.
When locating a type with Ctrl+N, you can use wildcards. Want all ViewModels? Type
*ViewModel(more...).
Transforming code
You can define what context actions you want available in .
Do you have multiple classes in the same file? Fix it fast. Press Ctrl+Shift+R on the file in the Solution Explorer and choose Move Types Into Matching Files (more...).
Rename anything, anytime, anywhere with F2. You can do it even in fewer steps - just type in a new name and hit Alt+Enter.
You can extract a method from a section of code using Ctrl+Alt+M.
Want to move a string literal to a resource file? Press Ctrl+Shift+R anywhere on the string and select Move To Resource (more...).
Type in new method signature (change the number or type of parameters, change the return type) and while the signature is highlighted with a grey frame, hit Alt+Enter to apply the Performing the refactoring in-place.
Placing your caret on a property, you can press Alt+Enter to change it from auto-property to a property with a backing field and vice-versa (more...).
Press Ctrl+F6 to change the signature of a method and see a preview before applying it. ReSharper will do the rest!
Think your code needs a good wash? Use Ctrl+Alt+F and run the Full Cleanup profile (more...).
Generating code
Generate various class members in seconds using the Generate command (Alt+Insert).
You can add a copyright header to all files via ReSharper | Options | Code Editing | File header text and then run code cleanup for the whole solution (more...).
Alt+Insert in the Solution Explorer can create files from your file templates .. and folders too.
Type
classand hit TAB. Want it public or internal by default? Change the corresponding live template (more...).
You can bind any member generation command to its own shortcut. Go to and look for commands starting with
ReSharper_Generate.
Create event subscriptions in XAML/ASP.NET WebForms/VB.NET using Alt+Insert and choosing Generate event subscriptions.
If you place your caret on a parameter in the constructor and hit Alt+Enter, ReSharper can create a field or property and initialize it for you.
Type
foreachand hit TAB. ReSharper will start a live template for smart loop generation with type and name suggestions (more...).
Unit testing
Use Ctrl+T,L to run all unit tests in the solution (more...).
Want to run some particular tests? Select them in editor, right-click and choose Run Unit Tests (more...).
Start typing in the Unit Test Explorer window to filter your tests by name.
Filter to failed tests while running them in the Unit Test Sessions Ctrl+F12 and look it up!
In ASPX pages, navigate to related files (CSS, JavaScipt, User Controls, etc.) with Ctrl+Shift+Alt+G.
Help and support
Check out which features work in which languages in the ReSharper feature matrix.
ReSharper support team is always there to help you. Use the ReSharper support web site to explore FAQ and knowledge base, or submit your support inquiry.
If you want a new feature to be implemented in ReSharper, feel free to post a feature request in ReSharper issue tracker. | https://www.jetbrains.com/help/resharper/Quick_Start.html | CC-MAIN-2019-18 | refinedweb | 1,211 | 66.64 |
VIDEOIO ERROR: V4L: can't open camera by index 0
Hello,
I'm triggering a Python file with PHP.
$return = shell_exec("/usr/bin/python3.6 create.py 2>&1")
Python File
import numpy as np()
Return this value
VIDEOIO ERROR: V4L: can't open camera by index 0
What is the problem?
are you sure, it HAS a camera plugged in ?
try with -1 as index.
Type following command on terminal to check list of video devices connected to your system. ls ~/../../dev/video* If video0 is not present then replug your camera.
@berak i tried this `cv2.VideoCapture(-1)
@ak1 file exists. Listed.
When you run the Python file, the camera turns on. However, it does't work when triggered by PHP.
oh, can it be that php does not have user rights to do that ?
It doesn't give anything like 'permission error'. When I changed the permissions I got 'permission error'. I don't think it's a permission error. | https://answers.opencv.org/question/199105/videoio-error-v4l-cant-open-camera-by-index-0/ | CC-MAIN-2019-35 | refinedweb | 163 | 77.74 |
ember
Ember - JavaScript Application Framework
npm install ember
Ember for Node
Ember.js is a framework for building ambitious client-side applications on the web. Now you can use the same Ember tools in node code and in node-based asset pipelines like Convoy.
Using This Package
Just add ember as a requirement to your package.json:
"dependencies": { ... "ember": "~0.9" }
In your code, you can load the entire Ember stack by just requiring the package. This will add Ember to the global namespace in your application.
require('ember'); MyApp = Ember.Application.create({ hi: function() { console.log('Hi! I'm an app!'); } });
If you don't want to use the entire Ember stack, you can just require the specific module that you want. For example, a lot of server side code just needs States for statecharting:
require('ember/states'); MyState = Ember.State.create({ });
Using Ember with Convoy
Building an Ember application in the browser is very easy when using Convoy. Just require ember in your main application file.
// In some JS module included by convoy: require('ember'); // <- convoy will automatically pull in all of Ember. UserView = Ember.View.extend({ template: Ember.Handlebars.compile('{{firstName}} {{lastName}}') });
If you want to store your Handlebars templates in a separate file, Ember for Node has a HandlebarsCompiler that will precompile the templates for you. Here is an example Convoy pipeline configuration:
pipeline = convoy({ 'app.js': { packager: 'javascript', compilers: { '.hbr': require('ember/packager').HandlebarsCompiler } } }); app = express.createServer(); app.use(pipeline.middleware());
This will now make
.hbr files available as modules. In your app code, you
can load the template via a normal require:
// user_view.js require('ember/views'); UserView = Ember.View.extend({ template: require('./user_template') // template in user_template.hbr });
For a fully functioning example of an application, check out the examples folder.
Building From Source
This project checks out the ember source and builds compiled copies for use in the released version. If you want to rebuild this from source, here is what you need to do:
- Make sure you have node.js and Jake installed globally. Once you have node.js installed you can install jake with the command
[sudo] npm install -g jake
- Also make sure you have Ruby 1.9.3 or later installed as well as bundler. Once you have ruby installed you can install bundler with
[sudo] gem install bundler
- Clone the node-ember repo
- From the repo directory run
jake vendor:setup. This should checkout the correct versions of ember and ember-data and set them up to build
- Run
jake dietto actually build the assets.
Note that you only need to run
vendor:setup once the first time you install the report or anytime the version of ember or ember-data changes. Afterwards, you should be able to run
dist just to rebuild.
ember and ember-data are linked into this project as git submodules. To update to a newer (or older) version of ember or ember-data, cd into the vendor directory and checkout the version you want. Then cd back to the top level of the repo and commit the updates into git. Once completed, run
jake vendor:setup again to update the contents.
IMPORTANT: The dist command will checkout whichever version of ember or ember-data are set in the submodule, so you must commit to git before rebuilding. | https://www.npmjs.org/package/ember | CC-MAIN-2014-10 | refinedweb | 554 | 58.99 |
C++ Basic Syntax – In the previous article, you wrote your first C++ program. But if you want to write more C++ programs then you will need to learn the syntax of C++ Programming Language. In this article, we will cover C++ Basic Syntax and C++ keywords.
C++ Keywords
Any Programming Language has a list of keywords. These keywords help us for constructing C++ Basic Syntax. C++ Keywords are a list of reserved words for this programming language. Each keyword has a special meaning and it can’t be changed by the programmer. The list of the C++ keywords are:
Now the above list of keywords doesn’t tell you anything. Do not worry about it. It’s absolutely normal because we will learn the meaning and usage of the most important part of C++ keywords and C++ Basic Syntax in this tutorial. You just have to remember that we can’t use these keywords to name constants, variables, or any other identifier’s name.
Now, let’s take a look at the program written in the previous article:
/ finishes its execution successfully return 0; }
This is a basic program and now we will explain the basic syntax used in this program.
What is #include ?
The program always starts with some lines containing include keywords. The include keyword is preceded by the “#” symbol. The symbol “#” means that it is a preprocessor directive. This will be discussed later in the “C++ Advanced” section of this tutorial. It is important to know that if you want to use any file from Standard Library, your include line should look like this:
#include
What is ‘using namespace std’?
By writing “using namespace <some_namespace>” we can use that namespace in our program. For example, if we want to use “std” namespace then we have to write below line
usingnamespace std;
If you want to use any symbol from std namespace by writing the below the line, all symbols in that namespace will become visible without adding the namespace prefix. A symbol may be for instance a function, class, or variable. So after writing “using namespace std” the symbol “cout” can be used directly as shown below:
cout<<"Welcome to TutorialCup";
But if you are not writing “using namespace std” then to get above output, you need to write code as below
std::cout<<"Welcome to TutorialCup";
What is a main() function in C++ ?
Any function in C++ is a block of the instructions to the compiler. The block of instructions is “highlighted” within “{ }” characters. For example:
#include <iostream> int main() {//start of block //block of instructions for main functions }//end of block
The main function is the starting function of any C++ program. The compiler first find and execute the main function in the program.
We will discuss the C++ Basic Syntax step by step in the next articles. Now it’s just a basic explanation of the HelloWorld program and details about C++ Keywords. | https://www.tutorialcup.com/cplusplus/basic-syntax-2.htm | CC-MAIN-2021-31 | refinedweb | 489 | 71.04 |
:
.
- We divide
our code into component (i.e piece of code, no matter it is class, namespace, assemblies).
- We conquer
by making sure that there are no dependency cycles between our components..
.
:
- The first was never to accept anything as true
if I did not have evident knowledge of its truth; that is, carefully to avoid
precipitate conclusions and preconceptions, and to include nothing more in my
judgements than what presented itself to my mind so clearly and.
I think that these
tenets apply so well to software development. Here is my personal
interpretation:
- The first tenet
can be seen as writing your test at least in the same time (or even before) as
you write your code to make sure that you are actually writing code that undoubtly
works (I had no occasion to doubt it).
- The second
tenet can be seen as separating concerns in order to separate difficulties to
code each concern better (divide each of
the difficulties I examined).
- The third tenet
can be seen as writing low level components first, in order to raise (step by step) the complexity of the code.
It also pinpoints that a total order between components should exist,
meaning that dependencies cycle are unacceptable.
- The forth tenet
can be seen as writing as many integration tests as needed to make sure to have
a high test code coverage ratio, ideally equal to 100% (I could be sure of leaving nothing out).
Undoubtly if Descartes
was alive today, he could be a great developer
) | http://codebetter.com/patricksmacchia/2008/02/10/layering-the-level-metric-and-the-discourse-of-method/ | crawl-003 | refinedweb | 253 | 56.69 |
08 March 2011 17:50 [Source: ICIS news]
HOUSTON (ICIS)--The ?xml:namespace>
Company CEO John Hess said that the
Specifically,
On 28 February, the
“The Gulf of Mexico is essential to the nation’s energy security,” he said, pointing out that 30% of
“We need to get our offshore drilling industry going again,” he added.
Hess spoke at the CERAWeek 2011 energy conference in
“We just need the political leadership in
On the whole, Hess said global oil producers were not investing enough in production capacity to keep up with rising demand.
“As demand grows in the next decade, we will not have the oil production capacity we will need to meet demand,” he warned.
“Supply will then have to ration demand and prices will skyrocket, with the likely outcome of bringing the world’s economy to its knees,” he continued.
“The $140/bbl oil price of three years ago was not an aberration – it was a warning.”
As such, steps such as increased deepwater drilling are desperately needed to fend off rapid growth in global population and transportation.
Other steps Hess suggested included higher fuel efficiency standards for automobiles and to maintain existing tax provisions to encourage drilling.
Hess said that renewable fuels could be part of the solution, but said that the industry “does not have the scale, timeframe or economics to materially change the outcome as much as we would hope”.
The CERAWeek 2011 | http://www.icis.com/Articles/2011/03/08/9441994/us-must-promote-gulf-deepwater-drilling-to-meet-oil-demand-hess.html | CC-MAIN-2014-10 | refinedweb | 238 | 56.39 |
Superscript Text in ui Button [Solved]
Hello all,
I am new to the Pythonista movement, just bought the app recently to try and explore some Python in a fun way. I have experience in C, C++, and Matlab, but not Python so I figured it was worth trying out.
I am currently working on writing an advanced version of the calculator.py tutorial, and I am trying to create buttons for things like "x^y" and "log base 10" in the usual mathematical notation but I cannot enter Button text in different sizes for each character nor can I find a way to print using super / sub scripts. Is there a clever way that I can use the custom attributes field for buttons to accomplish this? Or can I import an image into the button which is a depiction of these characters with no background?
I am trying to do this in the ui editor which comes with Pythonista.
Thanks for your help!
There are two options that I can think of:
- Use an image of the formula, like you suggested. You'll probably want to use the default "stencil" image mode, in which all visible parts of the image are "cut out" and displayed in the UI tint color (light blue by default, like the button text). That means you need an image with the formula on a transparent background, probably as a PNG. (A white background wouldn't work - because white is a visible color, it would also be treated as "foreground", and you'd just get a blue rectangle.)
- Construct the formula out of multiple labels and add them as subviews of the button. The UI designer doesn't allow this, but in code you can use the
add_subviewmethod on the button to add subviews to it. The easiest way to do that is probably to create an extra pyui file for each "special" formula. Then you can place the pyui onto the button using
button.add_subview(ui.load_view("x_pow_y"))for example. This also allows you to reuse the formula in other parts of your UI. (Unfortunately that is also only possible from code - it's not possible to "include" one pyui file in another using the UI designed.)
@omz Is adding subviews to buttons an intentional feature? Just wondering, because the UI designer doesn't allow it.
IIRC, buttons support attributedtext, via
objc_util.
There was some code in the forums about adding UIAttributedText to a ui.label, but I am. ot finding it atm. Same basic idea should work for a button.
@dgelessus To avoid the limitations of a button image, I often uses an ImageView as a subview of the button.
Here's an example how to use superscript in button created in Pythonista UI designer. Several comments:
- ObjC class used in this case is not descendant of
UIButtonclass
UIButtonin this case is added as subview
- Superscript works only and only if font supports it, for example x^2 works (supported by default iOS font), but x^y doesn't (not supported by default iOS font)
- If you'd like to fake it, you can use
NSFontAttributeNameand
NSBaselineOffsetAttributeName2')) range = NSRange(1, 1) attributed_string.superscriptRange')
And here's an example how to fake it if font doesn't support it.y')) range = NSRange(1, 1) UIFont = ObjCClass('UIFont') attributes = { ns('NSFont'): UIFont.systemFontOfSize(11), ns('NSBaselineOffset'): ns(5) } attributed_string.setAttributes_range_(attributes,')
Just tested the
superscriptRangeway on the iOS 11B4 and it does work. So, maybe the iOS 10.3.3 is broken in some way. Anyway it’s pretty ugly (way too up), so, you should go with smaller font & custom base line offset for your superscripts. At least you can control how it look like.
Thanks everyone for the replies, I really appreciate the input. I have been thinking about them but haven't had time to really dig in and understand some of the more advanced stuff, like using the obj-c approach. That seems really elegant, but I haven't quite wrapped my head around how the python wrapper for the obj-c works quite yet.
I will post again as soon as I have a chance to attempt some of these things, I have been struggling in the mean time with trying to get different views to draw based on orientation with only moderate luck.
Thanks to zrzka for a working solution!
I functionized his answer here:
def superscript(view, itemName, text, size, offset, startPos, length): #Get the UI object by name from the current UI view target_ui_item = view[itemName] #Create a obj-c Mutable Attributed String object and initialize with text NSMutableAttributedString = ObjCClass('NSMutableAttributedString') attributed_string = NSMutableAttributedString.alloc().initWithString_(ns(text)) range = NSRange(startPos, length) #Create an obj-c Font UIFont = ObjCClass('UIFont') #Define a List (?) of attributes attributes = { ns('NSFont'): UIFont.systemFontOfSize(size), ns('NSBaselineOffset'): ns(offset) } #Set the specific attributes of a specific range of the NS Mutable Attributed String attributed_string.setAttributes_range_(attributes, range) # ui_item_objc = ObjCInstance(target_ui_item) UIButton = ObjCClass('UIButton') for subview in ui_item_objc.subviews(): if subview.isKindOfClass(UIButton): subview.setAttributedTitle_forState_(attributed_string, 0)
Into this function, you should pass your current UI.View containing the UI element (in my case a button) which you want the superscripted string.
The second argument is the name of the UI element, in my case 'x_squared' <- the name of my button
The third argument is the text string that you want printed, in my case 'x2'
The fourth argument is the font size of the base character (I used 16)
The fifth arg is the offset for how high (or low, use negative) to offset the smaller character (I used 8)
The sixth arg is the string position to start the superscript string, (for me that was char 1)
The final arg is the length of the superscripted string (also 1 for me)
So the final call to this function looked like this (see first line below)
The second line below did a log base 10 string (slightly more complex call than an "x squared" button
superscript(self, 'x_squared', 'x2', 16, 8, 1, 1) superscript(self, 'log_base_ten', 'log10', 16, -10, 3, 2)
Hope this helps anyone who might need this in the future!
Thanks to everyone who helped me! | https://forum.omz-software.com/topic/4223/superscript-text-in-ui-button-solved | CC-MAIN-2021-17 | refinedweb | 1,035 | 60.65 |
As SilentStrike has stated use templates; then if you want to ensure that something is done when you use the function with a specific type, create a specialisation.
As SilentStrike has stated use templates; then if you want to ensure that something is done when you use the function with a specific type, create a specialisation.
What do you mean by difference? One runs on a standalone PC and the other runs across a network. If you want to know the differences involved in creating them then maybe a search engine or book may...
>I have to make sure the pointer points to a valid instance of any class that is derived from an abstract base class.
Then you shouldn't be using a void pointer. Use a pointer to the base class.
Yes if you insert an assignment operator after the subscript.
I'm not sure what you're up to, but you could use templates to overload on return type -
template <class T>
class population
{
public :
virtual T getindividual(){return 0;}
};
WinNT doesn't give you direct access to anything outside your processes virtual memory space without some form of driver or hack. Do a search for 'giveio' in your favourite search engine.
The syntax should be something like -
#include <iostream>
using namespace std;
void solver(int x){
if (x == 0)
throw ("x found to be 0") ;
As you've discovered, the compiler needs to see the full definition of a class before an instance of it can be constructed (it needs to know how big the object will be). The pointer version works...
An STL way might be something like -
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;
>When did I ever mention anything but the basic loop I made?<
Sorry I had no idea why you posted the asm. I assumed it was an attempt to justify your desicion not to turn on your compilers...
You could convert to the largest possible type. It doesn't sound like you're using templates properly, though.
>but would z be 159.000 etc... or would it come out with a completely random, something like 159.31415298?<
From the standard -
So it should be 159.000 if possible.
Well, I'm sure you probably didn't mean it but that could be optimised to one instruction quite easily if it could be established that it resulted in an infinite loop.
However, there probably...
>1) Let's see, optimization comes off in Dev-C++ unless you turn it on. Also, I know some people that keep it off just to make sure that things they don't want done aren't done. <
Then don't be...
> But the most important thing is that there things which you can't do in a high-level language, like interfacing directly with the hardware.<
This statement is false.
>I think that ASM will...
While this is true, portabiliy isn't just about crossing platforms but also about future portability. A hard coded asm executable will always remain the same. The theory is, if you were to upgrade...
>>In ygf's post, if you turned off compiler optimization<<
Why would you do that?
>>Although goto is shunned, it can be used efficiently in some situations.<<
Not this one. If you really...
What compiler are you using? There may be a debug version of operator new being called. Also, you should use the standard headers.
Perhaps you need to post some code; the description of your problem is as clear as mud. Have you implemented your own resevre and capacity functions for Hello? Or are you refering to the std::vector...
You create an array of 4 COption's then try and assign to 5 of them in your mainMenu() function.
>I'm not here for a long time, as someone else already said. But it's already irritating how these questions keep getting asked over and over and over again. <
We're not at all interested in your...
In that case -
*ReturnedObject = g->GeneralDX.d3d8;
You'll always have to de-reference the pointer to pointer otherwise your attempted return of an address will go out of scope.
What does g->GeneralDX.d3d8 return?
Check the FAQ.
Try -
*ReturnedObject = &g->GeneralDX.d3d8; | https://cboard.cprogramming.com/search.php?s=995ffe91ff32afebc01abb872b57fe92&searchid=7427357 | CC-MAIN-2021-43 | refinedweb | 711 | 75.2 |
A story about how Rx Framework saved my life for high frequency event processing
Sometimes, I learn about a technology that looks somewhat cool…
But I can’t find why. I know there is an idea, a spark, a sort of genius that I don’t understand quite yet, it’s here I see it, but out of my reach for now.
In this case, the technology was Rx Framework (also called Reactive Framework).
–Leap Motion I love you too, don’t be jealous
After reading the excellent Intro To Rx website, my reaction was : “That’s cool, but why changing from event-driven paradigm to reactive paradigm when the former worked for me since ages ?”
So I start reading article on Rx and got very upset about one thing : There were so many 101 articles teaching how to do basic stuff with RX but always, event-driven approach were better and easier, no article gave me a clear reason about why using reactive framework were easier than event-driven.
The only scenario mentioned was trading quotes… But I don’t work in trading so why should I care ?
Then I got an idea of project in WPF on the Leap Motion (link on GitHub), with some interesting metrics on data throughput by the leap motion:
Now, that’s what I call high frequency events… Finally I can try Rx Framework for real… and results are great ! It saved my life.
This article is not an Intro To Rx, and in fact, you don’t need to understand Rx to understand my article. This article is a real, practical case on how RX made my day better, an experience that I share with you. Feel free to generalize or contextualize to your own life, and dig in RX tutorials or numerous excellent channel9 videos.
Rx Framework introduces two types : Observable<T> that represent something that output events, were T is the type of your event.
And Observer<T>, that is someone that will observe/process these events.
I don’t really like to talk about Observer/Observable, because it reminds me pre-event driven programming when I was a poor Java guy… If C# invented events, it is not to go back to stone age years later.
I will using the term Observable<T>, I will use the term Event Stream or Event Source instead.
And instead of Observer<T>, I will use Event Processor.
This make me closer to the truth vocabulary of the Event Sourcing design pattern.
It makes so more sense to say “Throttle your event stream for 10 seconds”, that it is to say “Throttle your observable for 10 seconds”.
It makes more sense to “filter a stream” than “filtering an observable”.
I agree that for AI, it is semantically the same, but as human it is easy to picture yourself throttling and filtering a water stream than doing it to an “observable”.
What you will imagine, you will understand.
The first goal is to use leap motion data with RX to get FPS and fingers count in my debug window:
The first step was to implement leap motion’s base class Listener
Leap motion’s developers only implement the OnFrame, it is called when a new frame from the leap motion is coming.
OnFrame is called 30 to 100 times per second on a secondary thread.
My goal was to access these frames as an event stream is a class called ReactiveListener.
For that you can use rx’s Subject<T> class, this inherit from Observable<T> and you can push events T inside.
As you can see, the OnFrame was not very complicated
public override void OnFrame(Controller arg0)
{
NewFrameDetected.OnNext(arg0.Frame());
}
public IObservable<Frame> Frames()
{
return NewFrameDetected;
}
From here, I could finally calculate the FPS (Frame Per Second) with this nice expression in my ViewModel.
reactiveListener
.Frames()
.Timestamp()
.Buffer(2)
.ObserveOn(main.UI)
.Subscribe(o =>
{
var seconds = (o[1].Timestamp - o[0].Timestamp).TotalSeconds;
FPS = (int)(1.0 / seconds);
});
ObserveOn specify that the event processor (which is defined by Subscribe) should be executed on the SynchronizationContext of the UI Thread to update the UI.
Subscribe update the FPS property.
As you can see in the gif video at the beginning of this part, the Debug window shows how many fingers Leap Motion is detecting.
How is it implemented ?
reactiveListener
.FingersMoves()
.ObserveOn(main.UI)
.Subscribe(o =>
{
FingerCount++;
});
reactiveListener
.FingersMoves()
.Select(c => c
.ObserveOn(main.UI)
.Subscribe(cc =>
{
}, () =>
{
FingerCount--;
}))
.Subscribe();
To understand this code you need to understand what is a single FingerMove:
public IObservable<IGroupedObservable<int, Finger>> FingersMoves()
{
return Frames() /*frames*/
.SelectMany(f => f.Fingers) /*fingers*/
.GroupByUntil(f => f.Id,
g => g.ThrottleWithDefault(TimeSpan.FromMilliseconds(300)) /*duration*/);
}
So what does it means ?
First I start from the frame stream and extract every fingers in each frame with SelectMany.
Then I group them by Id, so I can get finger data stream for each of your finger.
Here is a simple representation of streams, also called Marble Diagram (time is the horizontal axis):
The second parameter of GroupByUntil return an event stream (called the “duration”), when the duration output an event, the group is considered “closed”. If fingers with the same id are coming after, GroupByUntil create a new group.
In this case, the duration output a value when its group stop receiving events for 300 ms.
So let’s go back to the expression to decrement the finger count:
I subscribe to every finger group that the groups stream outputs.
Then for each finger I see in this group, I do nothing.
The second parameter of Subscribe specify that when the group's stream is closed, then I decrement FingerCount.
It was very handy to represent fingers as stream, and grouping them in moves.
The leap motion sometimes misses a finger for 1 or 2 frame ( for something like 5 ms), it would be stupid to consider that since the finger was missing for only 2 frames, then the user want to make a new move.
300 ms is a timespan that an unalarmed person would not notice, and your can be sure that the leap motion will not miss a finger for 300ms by mistake, this make the perfect balance.
So before starting, what is GestSpace ?
GestSpace is a leap motion application to control your computer with your hand.
When GestSpace see your hand, it shows a customizable control panel.
A control panel is made of customizable tiles. (In fact, most of the tiles are configurable keyboard shortcuts associated with a gesture)
To use a Tile, you need to select it with your finger (Image 1)
Then lock it with your hand (Image 2)
Then move your hand (Image 3)
The gesture of your hand depends on the type of tile you are on. Image 3 shows how to modify volume.
So there is 3 state in this application:
This is expressed with the enumeration MainViewState as you can see in this class diagram.
Another point you can notice is that the ViewModel does not reference the previous ReactiveListener directly, but ReactiveSpace.
The difference between ReactiveListener and ReactiveSpace is that ReactiveSpace have expose streams highly coupled to my project whereas ReactiveListener can be used in other future projects.
ReactiveSpace exposes IsLocked, a boolean stream, that sends a value every times we should lock or unlock the tile.
So here is what happen in my MainViewModel.
spaceListener
.IsLocked()
.ObserveOn(UI)
.Subscribe(locked =>
{
if(this.State != MainViewState.Minimized)
State = locked ? MainViewState.Locked : MainViewState.Navigating;
});
How do I create the IsLocked stream ? Very easy.
public IObservable<bool> IsLocked()
{
if(_IsLocked == null)
{
var handIsPresent = listener
.Frames()
.SelectMany(f => f.Hands)
.Where(h => h.Fingers.Count >= 4)
.Select(s => true); //Step 1
var handIsAbsent = handIsPresent
.Throttle(TimeSpan.FromMilliseconds(200)); //Step 2
var handPresence =
handIsPresent
.Merge(handIsAbsent.Select(o => false)) /Step 3
.DistinctUntilChanged() //Step 4
.Replay(1); //Step 5
handPresence.Connect(); //The replay stream start listening the input stream
_IsLocked = handPresence;
}
return _IsLocked;
}
Step 1 – I create a stream of True boolean when there is a frame with a hand with 4 fingers. (handIsPresent)
Step 2 – I create a stream of True boolean when there is no value outputted from the first stream for 200 ms (Throttle with handIsAsbent)
Step 3 – I merge these two streams, and transform Trues of the handIsAbsent to False.
Step 4 – I keep only distinct consecutive values (the output stream can’t send two false or two true in a row)
Step 5 – I create a stream that will replay the last value of this stream when next subscribers will subscribe.
When I said it is easy, I should say instead : It is easy once you got your head wrapped in the problem for some hours… but now RX Framework expression are totally natural to me.
Now, how do I manage to control volume with the hand,
Each tile is associated with a class that inherit PresenterViewModel.These classes are responsible to subscribe to the ReactiveSpace when they are locked, and change the value of their property from event streams.
The PresenterViewModel for the volume is called ValuePresenterViewModel, currently it is only used for volume, you can’t bind keyboard shortcut on it.
On the WPF side, ValuePresenterViewModel is a styled progress bar, so the exposed properties should not surprise you.
But, look at closely the signature of the last constructor of ValuePresenterViewModel.
It waits for an event stream.
The constructor just listens for getValue, and update the Value property.
public ValuePresenterViewModel(double minValue, double maxValue, IObservable<double> getValue, Action<double> setValue)
{
this.setValue = setValue;
this.getValue = getValue;
this.MinValue = minValue;
this.MaxValue = maxValue;
this._Subscription = getValue
.Subscribe(d =>
{
_Value = Normalize(d);
OnPropertyChanged(() => this.Value);
});
}
private double Normalize(double value)
{
value = Math.Min(MaxValue, value);
value = Math.Max(MinValue, value);
return value;
}
Then Volume tile is just a matter of passing the right observable.
I used the excellent CoreAudioAPI.
MMDeviceEnumerator devEnum = new MMDeviceEnumerator();
MMDevice defaultDevice = devEnum.GetDefaultAudioEndpoint(EDataFlow.eRender, ERole.eMultimedia);
return new ValuePresenterViewModel(
minValue: 0,
maxValue: 100,
setValue: (v) => defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar = (float)(v / 100.0),
getValue: Observable.FromEvent<AudioVolumeNotificationData>(
o => defaultDevice.AudioEndpointVolume.OnVolumeNotification += o,
o => defaultDevice.AudioEndpointVolume.OnVolumeNotification -= o)
.Select(n=>n.MasterVolume)
.Merge(Observable.Return(defaultDevice.AudioEndpointVolume.MasterVolumeLevelScalar))
.Select(v=>(double)(v * 100.0)));
Ok… so now let’s look another example : the CyclePresenterViewModel that you can use for scrolling for example.
Contrary to ValuePresenterViewModel, you can script what the circle is doing when you draw a circle with your hand.
In this screenshot, I configure the Circle to simulate keyboard UP arrow 5 times when I go counter clock wise, and 5 times DOWN when I go ClockWise.
This is a mini language with 3 commands : PRESS, UP and DOWN, and each can take multiple arguments, there is a small intellisense to help you.
I also could have written : PRESS UP,UP,UP,UP,UP
The keyboard simulation was made possible by the excellent library InputSimulator.
Then, as the GIF image show you, I just need to turn my hand in the right direction to fire these keyboard shortcut.
The code of the subscription of the CyclePresenterViewModel is stupid, once again thanks to RX Framework.
I project the direction of one finger on the tangente of the circle at the current rotation point, and then, update the rotation. (In the setter of rotation, there is logic to decide when to fire the keyboard shortcut)
protected override IDisposable SubscribeCore(ReactiveSpace spaceListener)
{
return
spaceListener
.ReactiveListener
.FingersMoves()
.Concat()
.ObserveOn(UI)
.Subscribe(c =>
{
var v = c.TipVelocity.To2D();
var cos = Math.Cos(Helper.DegreeeToRadian(Rotation));
var sin = Math.Sin(Helper.DegreeeToRadian(Rotation));
var tan = new Vector((float)sin, (float)cos, 0);
var man = tan.Dot(v);
Rotation -= man / 100; //Some magic happens in the setter
});
}
I already show you how to turn an event into an event stream, or data from the leap to event stream.
But this is not limited to that.
With GestSpace, you can configure to go automatically to a tile when the foreground program change.
In the screenshot below, I specify that I want to go to Browser control when iexplore, firefox or chrome is on the front.
This way you can contextualize your gesture to what you are doing on your computer.
Here an example, I switch window, then I’m on codeproject, ready to scroll up/down, and go to previous/next page.
In the screenshot just before you see that I give a tip to the user about the current foreground program. How ?
By polling, with an event stream !
_ProgListener = new ForegroundProgramListener();
_ProgListener.ForegroundProcess
.ObserveOn(UI)
.Subscribe(pid =>
{
if(pid != _CurrentPid)
{
using(var p = Process.GetProcessById(pid))
{
CurrentProgram = p.ProcessName;
var tile = Tiles.FirstOrDefault(t => t.BelongsToFastContext(p.ProcessName));
if(tile != null)
CurrentTile = tile;
}
}
});
And here is the code of the ForegroundProcess.
ForegroundProcess
=
Observable.Interval(TimeSpan.FromMilliseconds(800))
{
var hwnd = user32.GetForegroundWindow();
uint pid = 0;
user32.GetWindowThreadProcessId(hwnd, out pid);
return (int)pid;
})
.DistinctUntilChanged();
RX Framework made my life easier.
It is a new way a thinking about events processing, it is cool for simple use case, but indispensable for handling high frequency events.
It takes time to wrap your head around the concept, I advice you to read Intro To Rx and check videos on channel9, it is worth it.
I got a bug in the framework for the GroupByUntil I documented here, except that point it was very cool.
The sources are on GitHub, feel free to experiment if you have your leap motion. :). | https://www.codeproject.com/Articles/653358/GestSpace-A-case-for-Rx-Framework-and-Leap-Motion | CC-MAIN-2018-13 | refinedweb | 2,240 | 55.13 |
Learning Machine Learning With Clojure and Cortex
Learning Machine Learning With Clojure and Cortex
Learn how to create easy-to-understand and ready-to-use neural networks from scratch and get instant results from your trained network using the Gorilla REPL.
Join the DZone community and get the full member experience.Join For Free
Insight for I&O leaders on deploying AIOps platforms to enhance performance monitoring today. Read the Guide.
It's not always easy to start something new. Machine learning is one of those programming skills that you may need to learn soon to go live with a new project but you don't really know where to start with it. Of course, you have already heard the hype, and you know the skill should be on your resume, but you never really got started.
While some of the simple tutorials are in Python, this article will use Clojure and Cortex for machine learning. You will learn how to create easy-to-understand and ready-to-use neural networks from scratch, as well as be able to get instant results from your trained network using the REPL dear to LISP.
Cortex is new, but it's a very strong alternative to existing machine learning frameworks. The fact that it is Clojure-based removes most of the surrounding boilerplate code required to train and run your own network.
Some examples I have created in the past with Cortex were used to classify cats and dogs or classify a large set of fruits. Both examples present how to write a neural network for image classification, but with this entry, we would like to go to the root of things and show you how to write an even simpler, but still effective, neural network — in just a few lines.
To highlight how to train and use the network, we will create a simple secret function (secret to the network, that is) and we will train the network to be able to compute inputs it has never seen before, quickly getting good results.
Cortex itself is a Clojure library that provides APIs to create and train your own network, including customizing input, output, and hidden layers, along with having an estimate of how good or bad the current trained network is.
The minimal Clojure project setup is a quite standard Leiningen setup, Leiningen being the de facto build tool for Clojure and a breeze to install. We will make use of the library
thinktopic/experiment which is a high-level package of the Cortex library.
We will also use one of my favorite REPLs, the Gorilla REPL, to have a Web REPL along plotting functions, which we will use later on.
(defproject cortex-tutorial "0.1-SNAPSHOT" :plugins [[lein-gorilla "0.4.0"]] :aliases {"notebook" ["gorilla" ":ip" "0.0.0.0" ":port" "10001"]} :dependencies [ [org.clojure/clojure "1.8.0"] [thinktopic/experiment "0.9.22"]])
The Gorilla plugin allows you to run a Web REPL, and you can start it by using the
notebook alias provided in the above
project.clj file. Here's how it looks as a simple terminal or console command:
lein notebook
You are all set up and ready to get going. In a Clojure namespace, you are going to define three things:
The secret function that the network is supposed to map properly.
A generator for a sequence of random inputs.
A dataset generator to provide the network for training. This will call the
secret-fnto generate both the input and output required to train the network.
In this project, the Clojure namespace containing the code is defined in
src/tutorial.clj and will be used by the two Gorilla notebooks.
(ns tutorial) (defn my-secret-fn [ [x y] ] [ (* x y)]) (defn gen-random-seq-input [] (repeatedly (fn[] [(rand-int 10) (rand-int 10)] ))) (defn gen-random-seq [] (let[ random-input (gen-random-seq-input)] (map #(hash-map :x % :y (my-secret-fn %)) random-input)))
With the Gorilla REPL started, head to the following local URL:
This is where the REPL is located, and where you can follow along with the notebook and type Clojure code and commands directly into the browser.
Preparation
The first task is to import some Cortex namespaces.
(ns frightened-resonance (:require [cortex.experiment.train :as train] [cortex.nn.execute :as execute] [cortex.nn.layers :as layers] [cortex.nn.network :as network] [tutorial :as tut] :reload))
The network and layers namespaces will be used to define the internals of your network. The
train namespace takes the network definition and datasets to produce a trained network. Finally, the
execute namespace takes the trained network and an extra input-only dataset to run the network with the provided input. The
tutorial namespace contains the code written above, with the hidden function and dataset generators.
Creating and testing the input generators will be your first step. The input generator produces a number of tuples made of two elements each.
(into [] (take 5 (tut/gen-random-seq-input))) ; [[9 0] [0 4] [2 5] [5 9] [3 9]]
The
random-seq generator can provide datasets with both input and output, internally using the hidden function.
(into [] (take 5 (tut/gen-random-seq))) ; [{:y [3], :x [1 3]} {:y [6], :x [3 2]} {:y [0], :x [0 2]}{:y [15], :x [3 5]} {:y [30], :x [6 5]}]
Now that you have an idea of what the generated data looks like, let's create two datasets: both of 20,000 elements.
teach-dataset will be used to tell the network what is known to be true and should remember what is true, while
test-dataset will be used to indeed test the correctness of the network and compute its score. It is usually better to have two completely different sets.
(def teach-dataset (into [] (take 20000 (tut/gen-random-seq)))) (def test-dataset (into [] (take 20000 (tut/gen-random-seq))))
We have two strong, fantastic datasets, so let's write your network. The network will be defined as a common linear network made of four layers.
Two layers will be for the expected input and output, while two other layers will define the internal structure. Defining the layers of a neural network is quite an art in itself. Here, we take the hyperbolic tangent as the activation function. I actually got a better-trained network by having two -based activation layers.
See here for a nice introduction to this topic.
The first layer defines the entrance of the network and its input, and says that there are two elements as one input, and that the label of the input is named
:x.
The last layer defines the output of the network and says there is only one element and whose ID will be
:y.
Using the Cortex API gives the small network code below:
(def my-network (network/linear-network [(layers/input 2 1 1 :id :x) (layers/linear->tanh 10) (layers/tanh) (layers/linear 1 :id :y)]))
All the blocks required to train the network are defined, so, as the Queen would say:
It's all to do with the training: you can do a lot if you're properly trained. — Queen Elizabeth II
Training
The goal of training is to have your own trained network that you can either use right away or give to other users so that they can use your network completely standalone.
Training is done in steps. Each step takes elements of the teaching dataset in the batch and slowly fits the blocks of each layer with some coefficients so that the overall set of layers can give a result close to the expected output. The activation functions we are using are in some sense mimicing the human memory process.
After each teaching step, the network is tested for its accuracy using the provided test dataset. At this stage, the network is run with the current internal cofficients and compared with a previous version of itself to know whether it performs better or not, computing something known as the loss of the network.
If the network is found to be better than its last iteration, Cortex then saves the network as a NIPPY file, which is a compressed version of the network represented as a map. Enough said; let's finally get started with that training.
(def trained (binding [*out* (clojure.java.io/writer "my-training.log")] (train/train-n my-network teach-dataset test-dataset :batch-size 1000 :network-filestem "my-fn" :epoch-count 3000)))
The output of the training will be in the log file, and if you look, the first thing you can see in the logs is how the network is internally represented. Here are the different layers, with the input and output sizes for each layer and the number of parameters to fit.
Training network: | type | input | output | :bias | :weights | |---------+-------------+-------------+-------+----------| | :linear | 1x1x2 - 2 | 1x1x10 - 10 | [10] | [10 2] | | :tanh | 1x1x10 - 10 | 1x1x10 - 10 | | | | :tanh | 1x1x10 - 10 | 1x1x10 - 10 | | | | :linear | 1x1x10 - 10 | 1x1x1 - 1 | [1] | [1 10] |Parameter count: 41
Then, each step/epoch gets the new score sees and whether the network was better and, in that case, saved.
| :type | :value | :lambda | :node-id | :argument | |-----------+-------------------+---------+----------+-----------| | :mse-loss | 796.6816681755391 | 1.0 | :y | |Loss for epoch 1: (current) 796.6816681755391 (best) nullSaving network to my-fn.nippy
The score of each step gives the effectiveness of the network, and the closer the loss is to zero, the better the network is performing. So, while training your network, one of your goals should be to get that loss value as close to zero as possible.
The full training with 3,000 epochs should only take a few minutes, and once it's done, you can immediately find out how the trained network is performing. If you are in a hurry, 1,500-2,000 is a good range for the number of epochs that will give you a compromise between speed and an already quite accurated trained network.
Once the training is done, you will find a new
my-fn.nippy file in the current folder. This is a compressed file based on the version of the trained cortex network.
A copy of the trained network,
mynetwork.nippy, has been included in the companion project. The loss of the network was pretty good, with a value very close to zero, as seen below.
Loss for epoch 3000: (current) 0.031486213861731005 (best)0.03152873877808952Saving network to my-fn.nippy
Let's give our newly trained network a shot, with a manually defined custom input.
(execute/run trained [{:x [0 1]}]) ; [{:y [-0.09260749816894531]}]
This is quite close to the expected 0*1=0 output.
Now, let's try something that the network has never seen before with a tuple of double values.
(execute/run trained [{:x [5 1.5]}]) ; [{:y [7.420461177825928]}]
Sweet. 7.42 is quite good compared to the expected result, 5*1.5=7.5.
Using the Network
As you saw, the trained network was saved in a NIPPY file. That file can be loaded and used by external "users" of your network. From now on, if you look at the provided notebooks, you can load the following note:
The users need a few namespaces. The
tutorial and
execute namespaces you've seen (i.e.
util) will be used to load the network from a file, and
plot is provided by the Gorilla plugin to plot values.
Later, we plan to plot the expected results vs. the network provided results.
(ns sunset-cliff (:require [cortex.nn.execute :as execute] [cortex.util :as util] [tutorial :as tut] [gorilla-plot.core :as plot] :reload))
Loading the trained network is a simple matter of using the
read-nippy-file function provided by Cortex.
(def trained (util/read-nippy-file "mynetwork.nippy"))
We didn't look at it before, but the network is indeed a map, and you can check its top-level keys.
(keys trained) ; (:compute-graph :epoch-count :traversal :cv-loss)
It is a good idea to check the number of epochs that the network has gone through, along with its current loss value.
(select-keys trained [:epoch-count :cv-loss]) ; {:epoch-count 3000, :cv-loss 0.030818421955475947}
You can confirm that the loaded network is given the same result as its freshly trained version from the last section.
(execute/run trained [{:x [5 1.5]}]) ; [{:y [7.420461177825928]}]
Now, let's generate a bunch of results with the loaded network and plot them. (Running the network on a fresh input set is now trivial for you!)
(def input (into [] (take 30 (tut/gen-random-seq)))) (def results (execute/run trained input))
And, of course, we can check a few of the result values produced by the network.
(clojure.pprint/pprint (take 3 results))
Plotting can be done with the Gorilla-provided plotting functions from the
gorilla-plot.core namespace. Here, we will take interest only in the output, and we will use Clojure's
flatten function to create a flat collection of output values as opposed to the sequence of vectors found in the results.
(plot/list-plot (flatten (map :y results)) :color "#ffcc77" :joined true)
After specifying a color, and knowing that
plot should use lines instead of dots, you can see the graph below straight in the browser REPL.
You can also produce a "composed" graph made of the expected results produced straight from the known or not-hidden function vs. results produced by the trained network.
(plot/compose (plot/list-plot (flatten (map :y results)) :color "blue" :opacity 0.3 :joined true) (plot/list-plot (flatten (map #(let [v (% :x)] (* (first v) (second v))) input)) :color "blue" :opacity 0.3 :joined true))
The two lines are actually too close and quite entirely overlap each other.
Retrain
From there, an interesting progression path would be to take the currently trained network and make it better by using more datasets and running the cortex
train-n function again.
(require '[cortex.experiment.train :as train]) (def teach-dataset (into [] (take 200 (tut/gen-random-seq)))) (def test-dataset (into [] (take 200 (tut/gen-random-seq)))) (def re-trained (binding [*out* (clojure.java.io/writer "re-train.log")] (train/train-n trained teach-dataset test-dataset :batch-size 10 :network-filestem "retrained" :epoch-count 10)))
Note: By specifying a new
network-filestem, you can keep a separate version of the updated network.
And with new datasets and a new training cycle, there is still a good chance to achieve a better network, and in that case, the network is saved again using the new file name.
Loss for epoch 3012: (current) 0.03035303473325996 (best)0.030818421955475947 Saving network to retrained.nippy
Conclusion
You have seen in this post how to train your own neural network to simulate the output of a known function. You saw how to generate and provide the required datasets used for training and how Cortex saves a file version of the best network.
Now, some ideas would be to:
- Try the same for a different hidden function of your own.
- Change the number of input and output parameters of the function and the network in the network metadata.
- If the network does not perform as well as expected, spend some time on the different layers of the network and find a better configuration.
The companion project can be found on GitHub.
TrueSight is an AIOps platform, powered by machine learning and analytics, that elevates IT operations to address multi-cloud complexity and the speed of digital transformation.
Published at DZone with permission of Nicolas Modrzyk . See the original article here.
Opinions expressed by DZone contributors are their own.
{{ parent.title || parent.header.title}}
{{ parent.tldr }}
{{ parent.linkDescription }}{{ parent.urlSource.name }} | https://dzone.com/articles/machine-learning-clojurecortex | CC-MAIN-2018-43 | refinedweb | 2,615 | 62.17 |
How do you round UP a number?
I know this answer is for a question from a while back, but if you don't want to import math and you just want to round up, this works for me.
int(21 / 5)4int(21 / 5) + (21 % 5 > 0)5
The first part becomes 4 and the second part evaluates to "True" if there is a remainder, which in addition True = 1; False = 0. So if there is no remainder, then it stays the same integer, but if there is a remainder it adds 1.
Interesting Python 2.x issue to keep in mind:
import math math.ceil(4500/1000)4.0math.ceil(4500/1000.0)5.0
The problem is that dividing two ints in python produces another int and that's truncated before the ceiling call. You have to make one value a float (or cast) to get a correct result.
In javascript, the exact same code produces a different result:
console.log(Math.ceil(4500/1000));5 | https://codehunter.cc/a/python/how-do-you-round-up-a-number | CC-MAIN-2022-21 | refinedweb | 169 | 80.51 |
New Active Directory Documents for IT Pros.
This posting is provided "AS IS" with no warranties, and confers no rights.
PingBack from
The entire process for joining the domain offline seem to work flawlessly, however, once you have joined the domain and restarted you are still stuck in as much as you can't login as you have no cached credentials, and the only way to get thenm is if you have access to a domain controller to process the logon. This requires you to be physically connected to the domain. Hence, you might as well wait until you are locally network attached to the domain and join in the normal manner.
If I'm missing something here please let me know.
Hi lmundy,
Thank you for the comment. You are not missing anything. The ODJ does not enable logon without network connectivity to a domain controller. I asked the djoin.exe developer about your comment and he replied that "to collect and apply the additional state to enable logon would require additional feature work, probably in more than just ODJ. There have been discussions on this but currently there isn’t any work planned by our team."
So the main benefit today is to reduce the time required and streamline the process for the domain join itself, and to frontload the domain join so if there are any problems with it, they might be exposed and resolved before the new domain client is rolled out in production environment.
We had feedback from some organizations that want to enable scenarios where they are rolling out 1000 VMs in a datacenter and they want to achieve this in an hour. In some cases the domain join itself was adding several minutes to each VM rollout, so cumulatively the domain joins could impede the high-speed, wide-scale rollout.
I think this is one of the main scenarios that djoin.exe was initially intended to target (as opposed to enabling a broader offline working scenario). I think the intent is that the next generation of System Center products will leverage it also.
But it's great to see customers finding it useful for their own scenarios as well, and for their feedback about how it can be improved.
Sincerely,
Justin
Is it required that the Windows 7/2008 R2 box come online within certain days once the offline domain join is done i.e. by default within 30 days (secure channel password reset cycle duration).
Hi Manishju,
Thanks for your question. The Djoin.exe developers said that the tool itself does not require the offline domain join to be completed within a specific time period. The secure channel password reset is initiated by the client machine so that will not become an issue.
The domain controller will not expire or cleanup the account by itself. An administrator would have to intervene, but many organizations run scripts every 30 to 60 days in order to clean up stale or unused computer accounts.
I will add this to the topic.
I hope that helps,
Justin [MSFT]
Active Directory Documentation Team
Appriciate your quick response. MS supporting community Rocks!!!
hi
this might be a noob question but long long will this process take if had to install over a newwork ?
Hi
This util would be great for us to deploy our lab images, only problem being is we have an odd DNS setup! We have a Domain DNS of domain.ad.sortdns.com and a public dns of sortdns.com, is there any way to fool the djoin util so it will insert the sortdns name as the SPN etc in the machine account?
Hi Jeffu,
I forwarded your comment/question to the feature development team. They said offline domain join was tested with disjoint DNS namespaces like you describe, and the SPN reflects the domain DNS name, just as you see. One way you might get this to work is to provision with the DNS name of the domain then rename (via script) after boot to the disjoint DNS suffix. Netlogon would then fixup the SPNs.
hope that helps,
Hi Justin, Thanks for the Blog.
We are re-imaging Windows XP machines with a fresh Windows 7 install. We are keeping the XP and Win 7 machines in separate OUs, meaning that somewhere in the provisioning process, the existing account would need to be moved to the Win 7 OU. We've developed vbscripts to do this with inconsistent results. Taking care of the domain join process on the "front-end" sounds like a promising way of assuring the process goes more smoothly.
My hope is that we could use djoin with the /reuse and /machineOU parameters to "prep" the existing account AND relocate it to the new OU using the /machineOU parameter. Is this scenario feasible?
Thanks in Advance for your help!
-Ben
Hi Justin,
I thought this djoin had a real world purpose for me, as I wanted to create a mechanism where staff in rural parts of the world could re-connect to a corporate domain without having to travel 8+ hours to get into an office (so that they would pass our VPN authentication
checks), I am now stuck where the rest of the people in this thread seem to be, where you get 99% of the way through just to get "no logon servers available" when trying to connect whilst off the network. Is there any extra switch that could be used to get
around this, or any future plans to make this tool so much more powerful?
Thanks,
Josh
Hi Josh,
You are correct that the offline domain-join process _by itself_ does nothing to either setup or ensure network connectivity to your corporate domain's domain controllers. The good news is that djoin.exe was extended to work in conjunction with Microsoft Direct
Access; this makes it possible to automatically install the minimal set of group policies and certificates necessary to bootstrap not only the domain-join state, but the network connectivity to a DA server. Once the machine is bootstrapped, normal Group Policy
behaviors and DA procedures take over.
Please see for more info.
Additionally: a bing search on "djoin.exe direct access" should yield several reports of this scenario working for actual customers.
I hope this helps,
Jay
Thanks for the quick and valuable response Jay,
I will look into this, it sounds like it could be exactly what I am after.
Apprecaited,
Josh | http://blogs.technet.com/b/activedirectoryua/archive/2009/05/26/new-djoin-exe-utility-in-windows-server-2008-r2.aspx | CC-MAIN-2015-27 | refinedweb | 1,079 | 69.31 |
A common problem which one needs to solve when dealing with graphs is to determine whether a given graph $G$ contains a cycle or not. As an example, one way to implement Kruskal's algorithm to compute the minimum spanning tree (MST) of a graph requires us to prevent the existence of cycles in the computed MST by manually detecting them and rooting them out as the MST is constructed (this version of Kruskal's algorithm does not use the union-find data structure). This post describes how one can detect the existence of cycles on undirected graphs (directed graphs are not considered here).
In what follows, a graph is allowed to have parallel edges and self-loops. On both cases, the graph has a trivial cycle. Our cycle detection algorithm will be written in Python, but implementing it in other languages should not be a difficult task if you understand the description given below. You can download the code shown in this post by clicking here.
Let's first start by introducing a simple implementation of a graph class which we will use later. A very simple class which contains all the functionality we need is defined below (it is based on the one presented here). This class does not explicitly store a list of vertices. Instead, it stores a dictionary (self.neighbors) which contains, for each vertex $v$, a list of its neighbors. A list of all vertices of the graph can be easily obtained from the keys of this dictionary, as shown in the member function vertices() below.
class graph: def __init__(self): self.neighbors = {} def add_vertex(self, v): if v not in self.neighbors: self.neighbors[v] = [] def add_edge(self, u, v): self.neighbors[u].append(v) # if u == v, do not connect u to itself twice if u != v: self.neighbors[v].append(u) def vertices(self): return list(self.neighbors.keys()) def vertex_neighbors(self, v): return self.neighbors[v]
Now we can proceed to detecting cycles. For undirected graphs, the algorithm is quite simple: start by selecting some unexplored vertex $v$ of $G$ and use breadth-first search (BFS) to explore every vertex which is reachable from $v$. We will refer to the set of vertices which are at a distance $n$ from $v$ simply as "the $n$-th layer". If a cycle exists, then one of the following will eventually happen as BFS progresses:
Consider case 1 first. If $u$ discovers $z$ first, it will set its layer value to $\textrm{layer}(u)+1 = n+1$. When $w$ discovers $z$, it will see that $z$ has a layer value large than $\textrm{layer}(w) = n$. Consider now case 2. In this case, some vertex $u$ from layer $n$ will find another vertex $w$ also on layer $n$, meaning $\textrm{layer}(u) = \textrm{layer}(w) = n$. Both cases lead us to immediately conclude the graph has a cycle.
The analysis above suggests we should do the following while going over the edges incident on vertices on the $n$-th layer to discover vertices on the $(n+1)$-th layer: if an edge connects the $n$-th layer vertex to an unexplored vertex, set the layer value of the unexplored vertex to $(n+1)$. If the edge leads to an already explored vertex, we must consider three possible cases:
In order to detect cycles also on disconnected graphs, we must go over every unexplored vertex $v$ and proceed as above. Every vertex which is reachable from a chosen starting vertex $v$ will not be used later as a starting point because it will be marked as explored by then. If $G$ is disconnected, some vertices will not be explored when we do BFS starting from the first unexplored vertex $v$, but as we go over the unexplored vertices in the main loop, we will eventually find every connected component of $G$.
Enough with the abstract talk. The function below implements the algorithm we just discussed and returns True if the input graph $G$ has a cycle or False otherwise:
def is_cyclic_graph(G): Q = [] V = G.vertices() # initially all vertices are unexplored layer = { v: -1 for v in V } for v in V: # v has already been explored; move on if layer[v] != -1: continue # take v as a starting vertex layer[v] = 0 Q.append(v) # as long as Q is not empty while len(Q) > 0: # get the next vertex u of Q that must be looked at u = Q.pop(0) C = G.vertex_neighbors(u) for z in C: # if z is being found for the first time if layer[z] == -1: layer[z] = layer[u] + 1 Q.append(z) elif layer[z] >= layer[u]: return True return False
As for the run-time complexity of the algorithm, notice that each edge is considered at most twice (once for each of its end vertices), and since we go over every vertex of the graph, the overall complexity is $O(m + n)$, with $m$ and $n$ being the number of edges and vertices respectively. | https://diego.assencio.com/?index=e83a797bcee562e2f1a4faa9293316ab | CC-MAIN-2021-21 | refinedweb | 840 | 60.24 |
Hi,
I had compiled and installed Open MPI with C/R support in the way Josh said. When finished, Open MPI had support and tools for C/R: ompi-checkpoint, ompi-restart.
And I try an example ( hello_c.c in examples folder, but I edit it with a for loop to print out "Hello..." 1,000,000 times)
But I get this error:
Error: The application (PID = 23573) failed to checkpoint properly.
Returned -1.
The steps what I had do:
# mpicc hello_c.c -o hello
# mpirun -np 4 -am ft-enable-cr hello
I get PID of this mpirun with another shell and do:
# ompi-checkpoint 23573
Error: The application (PID = 23573) failed to checkpoint properly.
Returned -1.
What's wrong with this error?
Could you help me an example about using C/R in Open MPI?
Hiep
hello_c.c
#include <stdio.h>
#include "mpi.h"
int main(int argc, char* argv[])
{
int rank, size, i;
MPI_Init(&argc, &argv);
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);
for(i=0; i<1000000; i++){
printf("%d Hello, world, I am %d of %d\n",i,rank, size);
}
MPI_Barrier(MPI_COMM_WORLD);
MPI_Finalize();
return 0;
} and Open-MPI-FT-CR-Draft-
> v1.pdf. I had built Open MPI from "trunk" which gotten by Subversion.
> But I don't know how to enable checkpoint/restart fault tolerance
> in Open MPI.
> So that, I get this error when I try this command: ompi-checkpoint.
> bash: ompi-checkpoint: command not found
> I want to ask you how to build and use checkpoint/restart feature
> in Open MPI.
> Please tell me in details, I'm a new user.
> Thanks!
> _______________________________________________
> users mailing list
> users@open-mpi.org
>
_______________________________________________
users mailing list
users@open-mpi.org | http://www.open-mpi.org/community/lists/users/att-3901/attachment | CC-MAIN-2015-32 | refinedweb | 285 | 75.61 |
A month of Flutter: initial theme
I don't have a full theme designed yet but I am planning on going in a clean and minimalist direction. So let's take the current default design and clean it up a little.
There are a couple of changes to the code for this theme cleanup. The first we'll cover is changing the status bar and navigation bar colors. The
SystemChrome change will go in the
main function. We'll also have to import
services to get access to
SystemChrome.
import 'package:flutter/services.dart'; void main() { runApp(MyApp()); SystemChrome.setSystemUIOverlayStyle( const SystemUiOverlayStyle( statusBarColor: Colors.white, systemNavigationBarColor: Colors.white, systemNavigationBarDividerColor: Colors.black, systemNavigationBarIconBrightness: Brightness.dark, ), ); }
Note that a full restart of the app is needed for the system UI color changes.
The next change is customizing the theme on
MaterialApp. These changes disable the debug banner, tell
MaterialApp to be in
light brightness mode, and set a few colors to white. The title is also changed to just
Birb.
MaterialApp( debugShowCheckedModeBanner: false, title: 'Birb', theme: ThemeData( brightness: Brightness.light, primaryColor: Colors.white, scaffoldBackgroundColor: Colors.white, ), home: const MyHomePage(title: 'Birb'), );
The next change is to center the title of the
AppBar and remove it's
elevation (shadow).
AppBar( title: Center( child: Text(widget.title), ), elevation: 0.0, ),
And the final change is to update and center the placeholder text. This will eventually turn into a widget to display when there are no images to show.
const Center( child: Text('No Birbs a birbing'), )
Now we have this nice clean base theme to continue building on.
If you want to learn more about theming Flutter apps, check out the Building Beautiful UIs with Flutter codelab. | https://bendyworks.com/blog/a-month-of-flutter-initial-theme | CC-MAIN-2018-51 | refinedweb | 283 | 52.46 |
I needed to create MD5 hashes to populate a password database for apache. This seemed like a very simple thing. So, when I wanted an MD5 hash in hex for my JSP app I expected to find a utility ready and waiting inside java. No such luck. No problem, I thought — I’ll just “google” it.
I was surprised to find that there are lots of half-baked solutions out there posted on various discussion forums, but none of them were solid, simple, and self-explanatory; or at least they didn’t look like code I would be comfortable with. So I decided to write it up and make it easy to find just in case someone else has the same experience.
My solution breaks out into three tiny functions that might be re-used lots of places.
import java.util.*; import java.security.*; String HexForByte(byte b) { String Hex = Integer.toHexString((int) b & 0xff); boolean hasTwoDigits = (2 == Hex.length()); if(hasTwoDigits) return Hex; else return "0" + Hex; } String HexForBytes(byte[] bytes) { StringBuffer sb = new StringBuffer(); for(byte b : bytes) sb.append(HexForByte(b)); return sb.toString(); } String HexMD5ForString(String text) throws Exception { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] digest = md5.digest(text.getBytes()); return HexForBytes(digest); }
HexForByte(byte b) gives you a two digit hex string for any byte. This is important because Integer.toHexString() will give you only one digit if the input is less than 16. That can be a real problem if you are building hash strings. Another tricky bit in this function strips the sign from the byte before converting it to an integer. In java, every kind of number is signed so we have to watch out for that when making conversions.
HexForBytes(byte[] bytes) gives you a hex string for any array of bytes. Each byte will be correctly represented by precisely two hex digits. No more, no less.
Wrapping it all up, HexMD5ForString(String text) gives you an MD5 digest in hex of any string. According to the apache documentation this is what I will want to put into the database so that mod_auth_digest can authenticate users of my web app. To see what started all of this look here:
With the code above in place I can now do something like:
HexMD5ForString( user + ":" + realm + ":" + password );
From the look of it, the Java code on the apache page looks like it will work; and it may be faster; but doing it my way the code is less obscure and yields a few extra utility functions that can be useful other places. | http://www.lifeatwarp9.com/2012/08/getting-an-md5-hash-in-hex-from-java/ | CC-MAIN-2019-35 | refinedweb | 429 | 72.76 |
Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office.
Dear all,
I have just noticed through my Eclipse version 3 that following packages =
are missing inside javax e.g.
javax.xml.namespace.*
javax.xml.xpath.*=20
and following are present
javax.xml.parser.*
javax.xml.transform.dom
javax.xml.transform.sax
javax.xml.transform.stream
I think there is a problem with the jar file that i have downloaded i.e. =
jaxp-api.jar n dom.jar) , can any body provide me the correct =
version/path of the file. becaz i have downloaded the jwsdp-1.5 and it =
contained these files under jaxp-api.jar n dom.jar
regards
Muhammad.
----- Original Message -----=20
From: Michael Kay=20
To: saxon-help@...=20
Sent: Sunday, February 20, 2005 11:42 PM
Subject: RE: [saxon] problems in configuring Saxon
I don't know Eclipse, I'm afraid. But check your copy of jaxp-api.jar =
- I'm pretty sure you'll find these two classes inside it.
I'm afraid Sun have made the download of the freestanding JAXP 1.3 =
very complicated and I can't make it any simpler for you. If you've got =
the files from jwsdp-1.5 then you're past that hurdle: check the =
contents of the JAR just to make sure, but I'm pretty sure you'll find =
they are there.
The IDE that I use (IntelliJ) allows you to have different JAR files =
in scope for different parts of your project. I don't know if Eclipse is =
similar, but that can sometimes lead to configuration problems of this =
kind.
Michael Kay
-------------------------------------------------------------------------=
---
From: saxon-help-admin@... =
[mailto:saxon-help-admin@...] On Behalf Of Muhammad =
Masoom Alam
Sent: 20 February 2005 16:07
To: saxon-help@...
Subject: Re: [saxon] problems in configuring Saxon
Hi,
thanks for the prompt reply
As for as the classpath is concerned, i am Using Eclipse and its =
never a problem with eclipse to set a path to an external Jar file , i =
means through project properties--> Add external jars, if u want me to =
do the manual excercise, i will do it and let u know about the results =
i.e. manualy setting the classpath , but normally with Eclipse it works =
i dont know why it is not working right now
but one thing, i have not downloaded these two files seperately but =
as part of sun jwsdp-1.5 and picked these 2 jar files (jaxp-api.jar n =
dom.jar ) from there. is this ok ??
regards
Muhammad.
PS:if u can plz give me the address of these files on the sun =
website, as it is difficult to find them seperately
----- Original Message -----=20
From: Michael Kay=20
To: saxon-help@...=20
Sent: Sunday, February 20, 2005 4:33 PM
Subject: RE: [saxon] problems in configuring Saxon
The classes javax.xml.namespace.QName and =
javax.xml.xpath.XPathVariableResolver are both in the jaxp-api.jar file, =
so if they aren't being found, then Java isn't finding this JAR file on =
your classpath. Check the classpath very carefully - Java doesn't give =
you any error messages if you spell the name incorrectly.
A useful test is to use exactly the same classpath, and type
javap javax.xml.namespace.QName
If that fails, then you know that the problem is nothing to do =
with Saxon.
If you still have problems, please let is know exactly what you =
are doing.
Michael Kay
------------------------------------------------------------------------
From: saxon-help-admin@... =
[mailto:saxon-help-admin@...] On Behalf Of Muhammad =
Masoom Alam
Sent: 20 February 2005 13:36
To: saxon-help@...
Subject: [saxon] problems in configuring Saxon | http://sourceforge.net/p/saxon/mailman/message/11846491/ | CC-MAIN-2014-35 | refinedweb | 622 | 66.64 |
If you read my last post – or if you just passing by got interested in the subject, here are a few follow-ups:
- When you create your custom Facet to store the bigger version of the image, make sure to decorate it with [DoNoIndex] as we don’t need the image to be indexed
[FacetKey(DefaultFacetKey)] public class UserPicture : Facet { public const string DefaultFacetKey = "UserPicture"; /// <summary> /// Base64 of the picture /// </summary> [DoNotIndex] public string Picture { get; set; } }
- xDB is not the best storage for images – Base64 encoded files are rawly 37% bigger than the original image. Although xDB can store files of any size, xConnect can eventually slow down when you have a high number of bigger files. Instead, you can save only the image reference on xDB, and store the file somewhere else.
- In the last article, when I say the Base64 was truncated on SQL Server, I was actually wrong.
It is only truncated on Management Studio, but the full information is on xDB. You can even read and write it, but still, it breaks Experience Profile when you use the native “Avatar” facet. | http://blog.peplau.com.br/pt_BR/part-2-xconnect-avatar-facet-breaking-experience-profile-follow-up/ | CC-MAIN-2020-34 | refinedweb | 186 | 57.44 |
Module: Apotomo::EventMethods
Overview
Introduces event-processing functions into the StatefulWidget.
Defined Under Namespace
Modules: ClassMethods
Instance Attribute Summary collapse
Instance Method Summary collapse
- #add_class_event_handlers ⇒ Object
- #respond_to_event(type, options = {}) ⇒ Object
Instructs the widget to look out for type Events that are passing by while bubbling.
- #trigger(*args) ⇒ Object
Fire an event of type and let it bubble up.
Instance Attribute Details
#page_updates ⇒ Object
Instance Method Details
#add_class_event_handlers ⇒ Object
#respond_to_event(type, options = {}) ⇒ Object
Instructs the widget to look out for type Events that are passing by while bubbling. If an appropriate event is encountered the widget will send the targeted widget (or itself) to another state, which implies an update of the invoked widget.
You may configure the event handler with the following options:
:with => (optional) the state to invoke on the target widget, defaults to +type+. :on => (optional) the targeted widget's id, defaults to <tt>self.name</tt> :from => (optional) the source id of the widget that triggered the event, defaults to any widget
Example:
trap = widget(:trap, :charged, 'mouse_trap') trap.respond_to_event :mouseOver, :with => :catch_mouse
This would instruct trap to catch a :mouseOver event from any widget (including itself) and to invoke the state :catch_mouse on itself as trigger.
hunter = widget(:form, :hunt_for_mice, 'my_form') hunter << widget(:input_field, :smell_like_cheese, 'mouse_trap') hunter << widget(:text_area, :stick_like_honey, 'bear_trap') hunter.respond_to_event :captured, :from => 'mouse_trap', :with => :refill_cheese, :on => 'mouse_trap'
As both the bear- and the mouse trap can trigger a :captured event the later respond_to_event would invoke :refill_cheese on the mouse_trap widget as soon as this and only this widget fired. It is important to understand the :from parameter as it filters the event source - it wouldn't make sense to refill the mouse trap if the bear trap snapped, would it?
#trigger(*args) ⇒ Object
Fire an event of type and let it bubble up. You may add arbitrary payload data to the event.
Example:
trigger(:dropped, :area => 59)
which can be queried in a triggered state.
def on_drop(event) if event[:area] == 59 | http://www.rubydoc.info/gems/apotomo/1.1.0/Apotomo/EventMethods | CC-MAIN-2017-39 | refinedweb | 329 | 51.89 |
Data Science Workshop 2 (Part 3): k-means Clustering: An Unsupervised Machine Learning Algorithm
Hi, this is Dr. Shahriar Hossain again. Today, we will discuss an unsupervised machine learning algorithm and use the scikit-learn machine learning library.
The concept I will discuss is called clustering. The specific algorithm that we will look at is called the k-means clustering algorithm. We will discuss what it is, and then we will write a python program. Knowing what it is, is more than half the work done. After that, the code will be pretty straightforward.
Here is the youTube video.
Contents
- 1 What does a clustering algorithm do?
- 2 What does the k-means clustering algorithm do?
- 3 Data description
- 4 Will k-means work with large datasets?
- 5 What are inputs of k-means clustering?
- 6 What is the out of the k-means clustering algorithm?
- 7 Scikit-Learn for machine learning algorithms
- 8 The code
- 9 Suggestion
- 10 Limitations of k-means clustering
What does a clustering algorithm do?
Suppose you have a data table. A clustering algorithm will tell you which data points or which rows are in the same group. That is, rows that have similar features will be in the same cluster.
What does the k-means clustering algorithm do?
The purpose of the k-means clustering is to discover k groups of objects in data. If k=2, you are looking for two groups. If k=3, you are looking for three groups. If k=4, you are looking for four groups or clusters, so and so forth.
Data description
Consider that we have this table of data.
It has three columns, or features or, attributes. It has 10 objects or 10 rows. Now, notice that some of the rows have larger values compared to the other rows. The k-means clustering algorithm with k=2, will be able to separate objects into two groups.
These rows will be in one cluster.
Let us say that these points will be in cluster 1. Notice that objects in cluster 1, have larger numbers in them.
The following rows will be in Cluster 2. Objects in Cluster 2 have smaller numbers in them.
That is, in clustering, rows that have similar features will be in the same cluster.
In real data, all the features might not have all large values, or, all small values. Some features in the same row might be small, some features in the same row might be large. Also, there can be many features or columns in your data, making the data much more complex to create groups manually.
Furthermore, it is difficult to find groups of similar rows if you have too many rows. Finding groups might be difficult, even if you only have several hundred rows.
I will use this simple data table in a Python program to keep the discussion simple.
Will k-means work with large datasets?
You could have a large data table. The core part of the code will remain the same. The k-means clustering algorithm is scalable, which means that the algorithm works very well with large data tables.
What are inputs of k-means clustering?
The input of k-means clustering is the data, and k, which is the number of clusters. That you are giving the data, and you are saying that you want to discover k clusters.
What is the out of the k-means clustering algorithm?
The output of the k-means clustering algorithm is cluster assignment for each row. That is, for each row, the algorithm will give you a cluster assignment, which is an integer. For our running example , with k=2, a possible set of output is sown below.
Scikit-Learn for machine learning algorithms
I will use scikit-learn machine learning library, where the state-of-the-art clustering algorithms are already available. The the scikit-learn package has the name sklearn in Python. If you use Google colab, it is already installed there.
If you use Jupyter notebook or regular Python, you need to make sure that scikit-learn is installed on your local computer.
Here is the pip command for installing scikit-learn and integrate it with your existing Python on your computer would be:
pip install sklearn
If scikit-learn is not already installed, the command will install and integrate scikit-learn with Python.
The code
You can download the Google colab/Jupyter Notebook file (ipynb) by extracting this zipped file: mykmeans.zip .
The Python code is as follows. You can use any regular Python editor (such as Spyder) and copy and paste the following code. Save the code in a file with .py extension and then run it.
from sklearn.cluster import KMeans import numpy as np data = np.array( [[20, 25, 18], [3, 2, 3], [6, 4, 5], [24, 21, 19], [22, 24, 21], [18, 20, 21], [4, 2, 3], [1, 5, 2], [19, 20, 19], [23, 19, 22]] ) km = KMeans(n_clusters=2).fit(data) print(km.labels_)
Suggestion
Please go ahead with some practice. Please make sure to change the data in the code. Use more columns and more rows. I am sure you will find exciting things with your own datasets.
Limitations of k-means clustering
There are several limitations of k-means clustering.
- Your data table cannot have strings or categories. Data must be all numbers.
- Another limitation is, you have to play with k, the number of clusters to see if you have meaningful clusters. Researchers have, for many years, argued that users providing the number of clusters is a limitation. In modern data science, “being able to provide an expected number of clusters, k” is considered a strength because the user has some control in generating meaningful results.
In the next part, we will see how we can visualize the data and the clusters that the k-means clustering algorithm has produced. See you in the next video soon.
The next part discusses how to visualize data points and clusters using Matplotlib. | https://computing4all.com/data-science-workshop-w2-p3-k-means-clustering-an-unsupervised-machine-learning-algorithm/ | CC-MAIN-2022-40 | refinedweb | 1,005 | 75.61 |
- 04 Nov, 2019 2 commits.
- 31 Oct, 2019 2 commits.
- 03 Oct, 2019 2 commits
- 12 Sep, 2019 2 commits
- 30 Aug, 2019 1 commit
isc_event_allocate() calls isc_mem_get() to allocate the event structure. As isc_mem_get() cannot fail softly (e.g. it never returns NULL), the isc_event_allocate() cannot return NULL, hence we remove the (ret == NULL) handling blocks using the semantic patch from the previous commit.
- 29 Aug, 2019 1 commit
- 09 Aug, 2019 1 commit
- 23 Jul, 2019 3 commits
- 21 Jul, 2019 2 commits
This commit changes the BIND cookie algorithms to match draft-sury-toorop-dnsop-server-cookies-00. Namely, it changes the Client Cookie algorithm to use SipHash 2-4, adds the new Server Cookie algorithm using SipHash 2-4, and changes the default for the Server Cookie algorithm to be siphash24. Add siphash24 cookie algorithm, and make it keep legacy aes as
- Witold Kręcicki authored
- 04 Jul, 2019 2 commits
- Thomas Jach authored
-
-.
- 27 Jun, 2019 2.
-
- 25 Jun, 2019 1 commit
The libxml2 have previously leaked into the global namespace leading to forced -I<include_path> for every compilation unit using isc/xml.h header. This MR fixes the usage making the caller object opaque.
- 24 Jun, 2019 1 commit
After a failed reload I noticed two problems: * There was a missing newline in the output of `rndc status` so it finished "reload/reconfig in progressserver is up and running" * The "reconfig in progress" note should have said "reconfig failed"
- 05 Jun, 2019 3 commits
- managed-keys is now deprecated as well as trusted-keys, though it continues to work as a synonym for dnssec-keys - references to managed-keys have been updated throughout the code. - tests have been updated to use dnssec-keys format - also the trusted-keys entries have been removed from the generated bind.keys.h file and are no longer generated by bindkeys.pl.
-.
- 22 Mar, 2019 1 commit
- 19 Mar, 2019 3 commits
- Michał Kępień authored
Some values returned by dstkey_fromconfig() indicate that key loading should be interrupted, others do not. There are also certain subsequent checks to be made after parsing a key from configuration and the results of these checks also affect the key loading process. All of this complicates the key loading logic. In order to make the relevant parts of the code easier to follow, reduce the body of the inner for loop in load_view_keys() to a single call to a new function, process_key(). Move dstkey_fromconfig() error handling to process_key() as well and add comments to clearly describe the effects of various key loading errors.
More specifically: ignore configured trusted and managed keys that match a disabled algorithm. The behavioral change is that associated responses no longer SERVFAIL, but return insecure.
- 15 Mar, 2019 2 commits
- 14 Mar, 2019 1 commit
- 08 Mar, 2019 1 commit
- 07 Mar, 2019 1 commit
- 06 Mar, 2019 1 commit
- Michał Kępień authored).
- 18 Feb, 2019 1 commit
- 06 Feb, 2019 1 commit
- 25 Jan, 2019 1 commit
- Witold Krecicki authored
- Use getters for isc_quota parameters, make fields private - Fix a potential data race with recursion clients limits logging
- 24 Jan, 2019 1 commit | https://gitlab.isc.org/isc-projects/bind9/-/commits/5fc8130822551dfab6e91ca3a1989efc6071df26/bin/named/server.c | CC-MAIN-2021-17 | refinedweb | 523 | 57.81 |
Module GlobalModule
End Module
the syntax <%# %> is used for data-bound control, you can use asp render block syntax instead
<TD><% GetMenu()%></TD>
and call the function and set the return value to this variable
and then use this variable in aspx.
The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!
fatihdurgut, I cannot call my function from code behind by setting a variable with a return value from that function because the function contains a lot of response.write statements.
That should be namespacing problem. When you create a module, by default the class will looks something like this,
Public Module GlobalModule
Public Function ReturnZero() As Integer
Return 0
End Function
End Module
You must call the function from aspx file with full qualified name syntax,
<%= RootNamespace.GlobalModule
Where RootNamespace is the root namespace or by default same as project name.
<%= RootNamespace.GlobalModule
gives me an error
RootNamespace.GlobalModule
Sorry if I wasn't being so clear, what I mean by "RootNamespace" here is the default namespace used by your project, or do the following:
1. In Solution Explorer, right click on the target project
2. Select Properties to open the project property page
3. Under the "Common Properties / General" there's a textbox for the project default root Namespace or if you never make any change to it, it has the same name with your project.
For example your project name is "Project1" the default namespace then is also "Project1". Again you can call any public function in a global module class with full qualified name.
<%= Project1.GlobalModule.Retu
Hope this time is clear enough.
I wrote Project1.ModuleName.Functi
and got an error: 'Project1.ModuleName' is not accessible in this context because it is 'Private'.
Module GlobalModule
End Module | https://www.experts-exchange.com/questions/20956406/calling-a-global-function-from-aspx-page.html | CC-MAIN-2018-17 | refinedweb | 301 | 56.86 |
).
Rich Outputs¶
One of the main feature of IPython when used as a kernel is its ability to show rich output. This means that object that can be representing as image, sounds, animation, (etc…) can be shown this way if the frontend support it.
In order for this to be possible, you need to use the
display() function,
that should be available by default on IPython 5.4+ and 6.1+, or that you can
import with
from IPython.display import display. Then use
display(<your
object>) instead of
print(), and if possible your object will be displayed
with a richer representation. In the terminal of course, there won’t be much
difference as object are most of the time represented by text, but in notebook
and similar interface you will get richer outputs.
Plotting¶
Note
Starting with IPython 5.0 and matplotlib 2.0 you can avoid the use of
IPython’s specific magic and use
matplotlib.pyplot.ion()/
matplotlib.pyplot.ioff() which have the
advantages of working outside of IPython as well.
One major feature of the IPython kernel is the ability to display plots that are the output of running code cells. The IPython kernel is designed to work seamlessly with the matplotlib plotting library to provide this functionality.
To set this up, before any plotting or import of matplotlib Jupyter Notebook and the
Jupyter QtConsole. It can be invoked as follows:
%matplotlib inline
With this backend, the output of plotting commands is displayed inline within frontends like the Jupyter notebook, directly below the code cell that produced it. The resulting plots will then also be stored in the notebook document.
See also
Plotting with Matplotlib example notebook
The matplotlib library also ships with
%matplotlib notebook command that
allows interactive figures if your environment allows it.
See the matplotlib documentation for more information. | https://ipython.readthedocs.io/en/stable/interactive/plotting.html | CC-MAIN-2018-34 | refinedweb | 306 | 64.2 |
- Code: Select all
#New Game, with variables, and better choices.
Money = 500
Wall_Health = 250
Wall_Rate = 25
Tax = 50
def prologue():
print "Welcome to A Tale of Kings, a sequel to A Tale of Things. This game is not like AToT, because you are not just choosing little tiny paths. Your choices carry on, and you deal with money, foreign relations, and other troubles."
Name = raw_input("What did you say your name was?")
print "Ah right. You are the good Sir " + Name + ", One of the members of a great council for a king. This king, who rules the small kingdom of Tarnor, is currently facing a dilemma. It appears that a larger kingdom by the name of Engon has taken a fancy to your Amethyst deposits. They have attacked!"
poop = raw_input("How much money do you think you have?")
print "You have a small amount of money to work with, 500 Amethyst Royals. 'Tis a pity that the Amethyst Royals are so easy to come by, they are worth practically nothing. You will have to be clever with your useage of these funds."
print
print "You also have a good sturdy wall made out of cardstock. It currently has 250 layers of cardstock, and you hope it will last. Unfortunately, every action that you do, the enemy attacks your wall for 25 damage. Work fast!"
print
print "You think that you might be able to survive this war if only you could get the assistance of one neighboring kingdom, Farlon. The problem is, the king of that nation has set a price, 25 Golden Dragons for his help (Equivalent to 1500 Amethyst Royals). You will have to see if you can raise the funds....)"
Start()
prologue()
def Start():
Action = raw_input("What would you like to do? Make sure to type in all caps. BUILD WALL, COLLECT TAXES, SHOP?")
if Action == 'BUILD WALL':
if Wall_Rate == 25:
print "You build up the wall 25 layers, but the enemy also attacks it for 25 damage. You might want to buy some building tools in the shop."
Start()
else:
Wall_Health = Wall_Health - 25 + Wall_Rate
print "You build your wall up some, just as your enemy attacks it. You heal the wall " + Wall_Rate + ". The Wall health is now " + Wall_Health
Start()
elif Action == "COLLECT TAXES":
Wall_Health = Wall_Health - 25
Money = Money + Tax
if Tax == 50:
print "You go out and collect 50 Amethyst Royals from your subjects. Your money is now " + Money + "Pretty good, but remember you can buy Tax collectors in the shop that will raise your tax rate. Also, the enemy attacked, so your wall's health is now " + Wall_Health
Start()
else:
print "You collect taxes from your subjects. Your money is now " + Money + ". The enemy attacked, so your health is now " + Wall_Health
Start()
elif Action == "SHOP":
Wall_Health = Wall_Health - 25
print "Welcome to the shop!"
print "We have many choices for you. Which menu would you like to see? Building tools? Tax Collectors? Or Weapons?" | http://www.python-forum.org/viewtopic.php?p=7866 | CC-MAIN-2016-22 | refinedweb | 488 | 82.44 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.