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 |
|---|---|---|---|---|---|
You can subscribe to this list here.
Showing
25
50
100
250
results of 88
The .fake files are only used by the build process to generate
OPT_Assembler.java on IA32; they are never used at runtime. The opt
compiler uses the same VM_Lister.java as the baseline compiler.
--dave
I know we can use command line argument like -X:base:mc=true or
-X:opt:mc=true to dump out machine code.
And I notice that for Intel architecture, the dump work is done in
VM_Lister.java. It seems fine in BaseBaseSemiSpace
configuration. But in FastAdaptiveSemiSpace configuration, VM_Lister.java is
created from VM_Lister.fake in
rvmRoot/rvm/src/vm/arch/intel/compilers/optimizing/ir/conversions/mir2mc/.
And the body of each method is empty.
How does the real dump work do? And under which reason do you choose to use
seperate VM_Lister.java file?
Hi,
my first guess would be that the classpath libs and Jikes RVM
source were possibly compiled with a different version of jikes? Not
being able to find $ classes suggests that perhaps something got
out-of-whack with the build process. Or something went a little wrong
with the classpath build process.
maybe try jbuild -trace to get more information.
you may also want to blow away the build directory & classpath
directory and start fresh. Sometimes the system isn't very good at
detecting that building classpath was only partially successfully (its
better than it used to be, but it may not be perfect).
--dave
VM_Thread.getCurrentThread() will only work if VM.runningVM (ie, not when
writing the bootimage).
--dave
Hi,
I'm trying to print the thread accessing the method areturn in
VM_Compiler.java.
/home/sita/rvmRoot/rvm/src/vm/arch/intel/compilers/baseline/VM_Compiler.java
I inserted the following hook in the method emit_areturn like
VM_Thread t = VM_Thread.getCurrentThread();
When I try to build rvm, I get the following error:
java.lang.RuntimeException: vm internal error at:
at com.ibm.JikesRVM.VM._assertionFailure
at com.ibm.JikesRVM.VM._assert
at com.ibm.JikesRVM.VM_Thread.getCurrentThread(VM_Thread.java)
at com.ibm.JikesRVM.VM_Compiler.emit_areturn(VM_Compiler.java)
Can anyone please explain me why I'm getting this error and how to correct
this?
Thanks,
Sita.
_________________________________________________________________
Gift-shop online from the comfort of home at MSN Shopping! No crowds, free
parking.
hello,
I am new to Jikes and I am trying to install it on Red Hat-9.0. I am
following the exact steps given in the user guide at.
The following is my config:
i-686, rh-9
Java Virtual Machine: Blackdown VM v1.4.1
Jikes Compiler: jikes-1.18
GNU Classpath 0.06
./jconfigure BaseBaseGenMS
and when I try to build it gives me this error when it calls jbuild.compile:
------------------------------------------------------
jbuild.compile:
Found 2 semantic errors compiling "java/lang/VMClassLoader.java":
7. import java.security.ProtectionDomain;
*** Semantic Error: Type java.util.Collections$SynchronizedMap$4 was not
found.
7. import java.security.ProtectionDomain;
*** Semantic Error: Type java.util.Collections$SynchronizedMap$SynchronizedMapEntry was not found.
jbuild.compile: The Jikes compiler exited with status 1 while we were
building the source file(s): Dummy.java
jbuild.compile: We invoked the Jikes compiler in the directory
/home/maverick/build/RVM.classes
jbuild.compile: With the command-line: /home/maverick/jikes-1.18/src/jikes
-nowarn -g +U -classpath .:rvmrt.jar Dummy.java
18 s
jbuild: Trouble while running "./jbuild.compile " (exit status 1); aborting execution
------------------------------------------------------
Any help would be very much appreciated.
thanks
regards
-Balaji.
Yes, it does look like some methods in VM_Lister have ordering mistakes.
If you have a corrected version, please submit a patch via the
contribution mechanism and I'll be happy to apply it. I'll also try to
take a look at the file myself and fix it before the next release, but if
you have already done the work it would be great to just have a patch to
apply.
cheers,
--dave
Hi,
In the file VM_lister.java, I suppose some methods have some mistakes about
the order of destination and source in the machine code output.
For example: The following two different methods have the same method body.
final void RRFD (int i, String op, byte R0, byte X, short s, int d) {
i = begin(i, op);
VM.sysWrite(right(isFP(op)?FPR_NAMES[R0]:GPR_NAMES[R0],
DEST_AREA_SIZE));
VM.sysWrite(right("[" + decimal(d) + "+" + GPR_NAMES[X] + "<<" +
decimal(s) + "]", SOURCE_AREA_SIZE));
end(i);
}
final void RFDR (int i, String op, byte X, short s, int d, byte R0) {
i = begin(i, op);
VM.sysWrite(right(isFP(op)?FPR_NAMES[R0]:GPR_NAMES[R0] + " ",
DEST_AREA_SIZE));
VM.sysWrite(right("[" + decimal(d) + "+" + GPR_NAMES[X] + "<<" +
decimal(s) + "]", SOURCE_AREA_SIZE));
end(i);
}
As analyzed from the VM_Lister.java file, I suppose in the second method
"RFDR", RFD should be the destination while R should be the source. Is this
really a bug?
Thanks
_________________________________________________________________
Tired of spam? Get advanced junk mail protection with MSN 8.
Thanks, Perry and Eliot.
Hiroshi
Perry Cheng wrote:
>
> I believe we do #3 for baseline compiler and #1 for the opt compiler.
>
> Perry
VM.sysWrite/sysWriteln.
--dave
Hi ,
I want to use Log in a function from the file VM_Compiler.java. I get
the following error.
import com.ibm.JikesRVM.memoryManagers.JMTk.Log;
^--------------------------------------^
*** Semantic Error: The type "com.ibm.JikesRVM.memoryManagers.JMTk.Log" has
default access and is not accessible here.
1847. Log.writeln("I'm in areturn");
^-^
*** Semantic Error: The type "com.ibm.JikesRVM.memoryManagers.JMTk.Log" has
default access and is not accessible here.
I don't know how to get rid of this error. As far as I know, Log is
the only class with which I can print something on the screen(similar to
VM_Interface.sysWriteln of jikes rvm 2.2 version). Can anyone please help me
with this.
Thanks,
Sita.
_________________________________________________________________
Share holiday photos without swamping your Inbox. Get MSN Extra Storage
now!
I believe we do #3 for baseline compiler and #1 for the opt compiler.
Perry
I have to run, but having seen the code, the approach is #3, unless it has
changed recently (which I doubt).
-- Eliot
Hi,
David P Grove wrote:
>
>
I don't have a clear handle on what's going wrong either. At UMass we're
using AIX 4.3 and gcc 2.95.2.1. Those symbols do seem to be defined and
exported from libgcc.a.
Since I couldn't see anything else wrong, I decided to upgrade our
machine to gcc 3.2.3. The installation of gcc failed. it's probably not
a coincidence, but it was in the module that implemented divdi3. Dave
found the following tidbit:
Unfortunately, I haven't managed to get that to work for me. I keep
getting errors saying "Bootstrap comparison failure!"
Chris
--
Chris Hoffmann -- Dept. of Computer Science/UMass at Amherst
One point that people sometimes overlook is that "trigger an allocation"
can happen in some unexpected ways. In particular any PEI (null pointer
exception, array bounds check, etc) can cause the allocation of an
exception object, so there are a number of non-obvious GC points in the
code. Similar things happen with unresolved references (trigger class
You might also want to try asking the opt compiler to print the final MIR
(-X:opt:final_mir=true). It is pretty close to the final machine code,
but still contains all of the symbolic information (types, field
locations, etc. etc). It makes it easier to interpret the machine code
dump. I typically dump both of them when I want to look at the code
generated.
--dave
In answer to your second question
2. It seems that yield point may cause GC be trigered because of thread
switching. But besides yieldpoints, are there any other points that GC
will
be automatically triggered?
I would say that one should first draw a distinction between triggering a
GC and participating in a GC that someone else started. The former arises
from an allocation that could not be satisfied or an explicit call to
trigger GC via System.gc. Participation in a GC comes from yielding in
general and can specifically come from either periodic yieldpoints in the
code (prolog, epilog, backward branches) or explicit calls to the
scheduler yield.
Perry
Hi,
Here is a question about the x86 machine code generated by rvm under
configuration FastAdaptiveSemiSpace.
The source is as follows (just a method)
static long f(int k) {
long l=0;
for(int i=k*32767;i<(k+1)*32767;i++)
l+=i;
return l;
}
I used the opt-compiler option -X:opt:mc=true under configuration
FastAdaptiveSemiSpace to generate the following machine code correspondingly
but with my own comments in order to make my question clear.
000000| CMP esp -68[esi] | 3B66BC
000003| JLE 56 | 0F8E00000000
000009| PUSH -80[esi] | FF76B0
00000C| MOV -80[esi] esp | 8966B0
00000F| PUSH 15156 | 68343B0000
000014| MOV -20[esp] ebx | 895C24EC
000018| MOV -16[esp] edi | 897C24F0
00001C| MOV -12[esp] ebp | 896C24F4
000020| ADD esp -20 | 83C4EC
000023| CMP -60[esi] 0 | 837EC400
000027| JNE 60 | 0F8500000000
-----I think these two instutions are related with "yield point". As can be
seen from several lines from the bottom instructions, the call address will
also differ in different kind of yield points.
1. Does this mean that different address correspond to "yieldpoint_prologue,
yieldpoint_backedge, yieldpoint_epilogue"? And what are the specific
operations of those different yield points?
2. It seems that yield point may cause GC be trigered because of thread
switching. But besides yieldpoints, are there any other points that GC will
be automatically triggered?
3. What value does -60[esi] point to?
4. In the second jump instruction, how to compute the jump target address?
Does the number "60" give any implication?
00002D| MOV edx 0 | BA00000000
000032| MOV ecx 0 | B900000000
000037| MOV ebx eax | 89C3
000039| IMUL ebx 32767 | 69DBFF7F0000
00003F| JMP 31 | E900000000
000044| MOV edi ebx | 89DF
000046| MOV ebp edi | 89FD
000048| SAR ebp 31 | C1FD1F
00004B| ADD ecx edi | 01F9
00004D| ADC edx ebp | 11EA
00004F| INC ebx | 43
000050| <<< 00003F
000050| CMP -60[esi] 0 | 837EC400
000054| JNE 64 | 0F8500000000
00005A| MOV edi eax | 89C7
00005C| INC edi | 47
00005D| IMUL edi 32767 | 69FFFF7F0000
000063| CMP ebx edi | 39FB
000065| JLT -35 | 7CDD
000067| CMP -60[esi] 0 | 837EC400
00006B| JNE 68 | 0F8500000000
000071| MOV eax edx | 89D0
000073| MOV edx ecx | 89CA
000075| MOV ebx [esp] | 8B1C24
000078| MOV edi 4[esp] | 8B7C2404
00007C| MOV ebp 8[esp] | 8B6C2408
000080| ADD esp 24 | 83C418
000083| POP -80[esi] | 8F46B0
000086| RET 4 | C20400
000089| <<< 000003
000089| INT 67 | CD43
-----What does this interrupt do?
00008B| JMP 9 | E979FFFFFF
000090| <<< 000027
000090| CALL [43002A44] | FF15442A0043
000096| JMP 45 | EB95
000098| <<< 000054
000098| CALL [43002A4C] | FF154C2A0043
00009E| JMP 90 | EBBA
0000A0| <<< 00006B
0000A0| CALL [43002A48] | FF15482A0043
0000A6| JMP 113 | EBC9
Thanks!
_________________________________________________________________
The new MSN 8: smart spam protection and 2 months FREE*
Hi,
I am trying to build and run Jikes RVM version 2.3.0.1 on AIX/PowerPC.
The building process of the VM and GNU classpath was doing fine.
However, when I run the VM, I got an error inside VM.boot (). The
stacktrace is shown as follows. It seems that some symbols are not
found inside JikesRVM. Is it a GCC/linker problem? FYI, I am using GCC
version 2.95.2. I also have tried both the system ld and GNU ld and both
linker give the same assertion error shown below.
Are there any way to fix the problem? Thanks in advance.
david
JikesRVM: error loading library
/home/ibmsp/cwong1/working/rvmBuild/libjavaio.a: 0509-130 Symbol
resolution failed for /home/ibmsp/cwong1/working/rvmBuild/libjavaio.a
because:
0509-136 Symbol __divdi3 (number 26) is not exported from
dependent module JikesRVM.
0509-136 Symbol __eprintf (number 27) is not exported from
dependent module JikesRVM.
0509-192 Examine .loader section symbols with the
'dump -Tv' command.
error loading library: /home/ibmsp/cwong1/working/rvmBuild/libjavaio.a
java.lang.UnsatisfiedLinkError
at
com.ibm.JikesRVM.VM_DynamicLibrary.<init>(VM_DynamicLibrary.java:47)
at
com.ibm.JikesRVM.classloader.VM_ClassLoader.load(VM_ClassLoader.java:82)
at java.lang.Runtime.loadLibrary(Runtime.java:188)
at java.lang.System.loadLibrary(System.java:665)
at java.io.File.<clinit>(File.java:98)
at com.ibm.JikesRVM.VM.runClassInitializer(VM.java:392)
vm internal error at:
-- Stack --
Lcom/ibm/JikesRVM/VM; sysFail(Ljava/lang/String;)V at line 966
Lcom/ibm/JikesRVM/VM;
_assertionFailure(Ljava/lang/String;Ljava/lang/String;)V at line 460
Lcom/ibm/JikesRVM/VM; _assert(ZLjava/lang/String;Ljava/lang/String;)V
at line 440
Lcom/ibm/JikesRVM/VM; _assert(ZLjava/lang/String;)V at line 431
Lcom/ibm/JikesRVM/VM; _assert(Z)V at line 420
Lcom/ibm/JikesRVM/VM_Thread; terminate()V at line 994
Lcom/ibm/JikesRVM/VM_Runtime;
deliverException(Ljava/lang/Throwable;Lcom/ibm/JikesRVM/VM_Registers;)V
at line 877
Lcom/ibm/JikesRVM/VM_Runtime; athrow(Ljava/lang/Throwable;)V at line 564
Lcom/ibm/JikesRVM/VM; runClassInitializer(Ljava/lang/String;)V at
line 394
Lcom/ibm/JikesRVM/VM; boot()V at line 166
JikesRVM: exit 124
I've had to do a similar thing: insert instrumentation that had to be able
to do pretty much anything.
The solution I implemented, and one you may like to consider, allows me to
insert a counter instruction with arbitraty arguments; this instruction
behaves just like a normal counter instruction for sampling purposes,
etc., but when lowered to LIR, it gets converted to a function call to the
function of my choice, with the appropriate arguments.
So all I have to do is write a function in Java to do whatever data
collecting I want, and insert one of my counters into the HIR stream that
passes it the arguments it needs.
In your case, you would write a function that takes different Objects, and
stores their actual runtime types (along with, certainly, the bytecode
line the counter occurs on). Then you'd insert a bunch of these counters
in the appropriate places, with the Objects in question as arguments.
The way I did it was to create a new instruction type (instead of
INSTRUMENTED_EVENT_COUNTER, SUPER_INSTRUMENTED_EVENT, or something). This
instruction takes a variable number of arguments. I also added a new
counter manager, VM_CounterFunctionManager (as opposed to the existing
VM_CounterArrayManager) that dealt with this new instruction and lowered
it to a function call. I had to patch up some other code, such as Matt
Arnold's sampling code, to recognize the super counter as instrumentation
code, but there's not much to do other than that.
If you do like this solution, hopefully this is a good enough start for
you, or I'd be happy to provide more information or code.
AJ
On Tue, 18 Nov 2003, Brian Tanner wrote:
> I see where you're coming from, let's explore this a little further.
>
> I think this isn't quite going to do what I need, but it may. You see,
> I'd like to do this instrumentation without having to know ahead of time
> what the actual potential classes are. IE, if a class that I don't know
> about (a subclass of C maybe) is loaded after I've been executing for a
> while, I'd still like to be able to profile this.
>
> This is why I was thinking that it would make sense to actually lookup
> the type at runtime. I figured there would be a quick instruction I
> could throw in that would have the affect of:
> Void Foo(A someParam){
> String Key="Foo:"+someParam->getTib()->getType();
> }
> Of course this would have to be HIR code...
>
> The end goal of this is to create a dynamic profile at runtime that an
> optimization phase my colleague is writing can make intelligent
> decisions when optimizing the method.
>
> The class loading issue is not the most important thing though, I can
> live without it. If I was to do this instrumentation at the bytecode
> level, would I just update the BC2IR code to add the code you mentioned?
> If so, I guess I'd have to peek at the class hierarchy to look up the
> currently loaded subclasses of A?
>
> My intuition also tells me (and I could be wrong here) that a byte code
> level instrumentation would store the information at the program level.
> Would there be a decent way for an optimization pass to get at these
> values at dynamic recompilation time?
>
> Thanks in advance for your help here!
>
> Brian Tanner
> University of Alberta
> btanner@...
>
> ==== Original Message ====
> If that's only information you need, I would say instrumentation at
> bytecode level is much easier. For exmaple, at the beginning of your foo
>
> method, you can add:
> if (someParam instanceof A)
> Acount ++;
> else if (someParam instanceof B)
> Bcount ++;
> else
> Ccount ++;
>
> Cheers,
> Feng
>
>
>
>
> _______________________________________________
> Jikesrvm-researchers mailing list
> Jikesrvm-researchers@...
>
>
I'm having trouble running Jikes RVM on AIX 5.1/PowerPC
involving the handling of traps. I think it is a bug in my aix
installation ?
I included a little C-program, or for clarity I also include here a link:
The outcome of this on my aix 5.1 box is:
signum: 11, address: deadbeef
context->sc_jmpbuf.jmp_context.o_vaddr: 0
context->sc_jmpbuf.jmp_context.iar: 10000454
While on some other aix 4.3 machine it gives the more correct outcome:
signum: 11, address: deadbeef
context->sc_jmpbuf.jmp_context.o_vaddr: deadbeef
Kris.
Oh, Yes
Sorry for my mistake.
feng
Sunil V. Soman wrote:
>>rvm/src/vm/compilers/optimizing/optimizations/global/liveness/OPT_Liveness.java
>>Revision 1.25.
>>
>>
>
>For other folks who might be interested, I think he meant
>OPT_LiveAnalysis.java
>
>Thanks!
>Sunil
>
>_______________________________________________
>Jikesrvm-researchers mailing list
>Jikesrvm-researchers@...
>
>
>
> rvm/src/vm/compilers/optimizing/optimizations/global/liveness/OPT_Liveness.java
> Revision 1.25.
For other folks who might be interested, I think he meant
OPT_LiveAnalysis.java
Thanks!
Sunil | http://sourceforge.net/p/jikesrvm/mailman/jikesrvm-researchers/?viewmonth=200311&style=flat | CC-MAIN-2015-32 | refinedweb | 2,963 | 57.47 |
Application Programming with ZAppSvr
The purpose of this document is to help the developer be productive quickly. In order to get started there are a few things that you need to know, and examples are the best way to illustrate how to apply knowledge. Since ZAppSvr has so many potential uses, we will need separate documents to highlight various features. We'll start here with the programming basics to get you started.
For the purposes of this document we will presume that you are using the NetBeans IDE 5.5.1 () for development. If you are using a different IDE, the information will still be helpful in setting up your programming environment. A more experienced user, or a developer with special requirements may set things up differently, but we are assuming a lower level of experience so we don't fail to cover some basic information you might need.
Writing an application for ZAppSvr simply consists of writing a Plugin class. This single class is pooled and accessed by as many threads as you have configured ZAppSvr to use. Your Plugin is handed references to all the data needed by your Plugin, which you can use to meet your service design goals.
Global data that all threads (instances of your Plugin) need, is stored in a globally accessible Hashtable (globalHash). This mechanism can be used any way you prefer.
A method in your Plugin called runOnceInit(), will be used by ZAppSvr to set up your objects in the global Hashtable so that only one instance of each object is created, and all needed structures are prepared at runtime. If, for example, you have set up ZAppSvr for 500 threads, the runOnceInit() routine will only be run once to establish the starting run environment. The runOnceInit() method will not be executed for the other 499 instances of your plugin. This avoids duplicate object creation at startup.
In addition to this, your application can access ZCReplicator services. These services (currently just two, more to follow) allow you to transfer files to, and delete files from, server groups in a load balanced deployment environment. This means you can receive a file and place it on all servers in a defined server group. You can also delete a file easily. We’ll discuss these two methods in greater detail in our example application.
ZAppSvr is designed to leverage load balancing as a fundamental and integrated part of this application server environment. Application clustering becomes a natural part of your application, just by using the ZAppSvr application deployment model. We’ll illustrate this in our examples.
The following is an example Plugin file, that shows you the basic skeletal structure of your Plugin class. This basic structure is all you need to get started writing your Plugin. In our example, no matter what you request you are returned a short html message “Hello World”.
You can use this little program to verify that your debugging environment is set up properly. You should have your IDE configured so that you can start your project in the debugger and step through the Plugin code. Note that the execute() method is what is executed when a request is received, provided that the request meets the requirements of the authentication list (see configuration).
import java.awt.*;
import java.util.*;
import java.text.*;
import java.net.*;
import java.io.*;
public class Plugin
{
private Object[] o = null;
private String[] reqArray = null;
private String[] strings = null;
private String ipAddress = null;
private String hostName = null;
private byte[] postData = null;
private byte[] retData = null;
private Hashtable globalHash = null;
private Vector outHdrAdd = null;
private Vector customLog = null;
private InetAddress inetAdr = null;
private Boolean isSSL = null;
private ZAppSvrUtilities zsu = null;
public Plugin()
{
}
public void runOnceInit(Hashtable h)
{
// initialize any classes you need here, and add them to Hashtable h
}
public void execute( Object[] inobj )
{
o = inobj;
reqArray = (String[])inobj[0]; // the complete request header
ipAddress = (String)inobj[1]; // the ip address of the requestor
globalHash = (Hashtable)inobj[2]; // the repository of global objects
outHdrAdd = (Vector)inobj[3]; // add items to the return header
customLog = (Vector)inobj[4]; // custom logger
strings = (String[])inobj[5]; // group and hostname information
postData = (byte[])inobj[6]; // POST request data
hostName = (String)inobj[8]; // hostname for this request
inetAdr = (InetAddress)inobj[9]; // inetAddress object
isSSL = (Boolean)inobj[10]; // is request from SSL
zsu = (ZAppSvrUtilities)inobj[11]; // useful utilities
retData = myFunc(); // place your code here... whatever you want to do..
o[7] = retData; // THIS LINE IS REQUIRED unless you just hand the data directly to o[7];
}
public byte[] myFunc() // see ZeroPoint application Server How-To for more details
{
return (new String("<html>Hello World</html>")).getBytes();
}
}
ZAppSvr has a few utilities that allow you direct access to internal services you can leverage in writing your applications. Here is the interface that describes these services:
public interface ZAppSvrUtilities
{
// ZCReplicator routines
public void sendFileToGroup(String groupname, String path, byte[] data);
public void deleteFileFromGroup(String groupname, String path);
// Generally useful routines
public int cvtToInt(String s);
public long cvtToLong(String s);
public String[] cvtVectToStringArray(java.util.Vector envVec);
public byte[] setHtmlRetData( String ststr, java.util.Vector outHeaderAdd, byte[] outputData );
// Load Balancer Routines
// returns IP address, port of best choice for group
public String[] getBestSvrChoice(String groupname);
public void setSvrBusy( String groupname, String ipaddress );
public void clrSvrBusy( String groupname, String ipaddress );
}
ZCReplicator routines provide you with the means to distribute and maintain files on servers that are part of a load balanced group. On high demand networks, maintaining mirrored file sets is simplified by using these tools. There are other tools that cover these issues, but there are times and applications where having a built in mechanism can be extremely helpful. For example if you have a web service where customers upload images that need to be replicated on other servers in the group, this utility is very nice. Deleting existing images pose the same issues.
Since ZAppSvr is an application server and load balancer, we need these load balancer tools to identify (where needed) which server would be best to use, and to notify ZAppSvr that our service is using that server. You can use getBestSvrChoice() to return the best server to use for your current operation. The String[] that is returned, contains the IP address in position 0, and the port in position 1.
Once you’ve selected the server, you need to use setSvrBusy( groupname, ipaddress ) to signal the load balancer that a process is running on that target server. clrSvrBusy( groupname, ipaddress ) is used after the process is complete to signal that the server is no longer in use.
public byte[] setHtmlRetData( String ststr, java.util.Vector outHeaderAdd, byte[] outputData )
Usage goes something like this; You create a dynamic response, (some html code) and you want to return that data to the requestor. To do this you need header information, status codes, etc. In this case you might call the routine like this:
retData = setHtmlRetData( "200", outHeaderAdd, outputData );
In this example the return code was 200, outHeaderAdd is a Vector reference for modifying the return header that is passed into the execute() method in your plugin. outputData is the data you want to return in byte[] form. o[7] is a passed reference to your plugin that provides direct access to the data that is sent to the requestor. It is very handy for web service design. Usage is optional.
The other utilities provided are routines that we find we use often, and are provided in case they might be of benefit to the developer.
The two methods cvtToInt() and cvtToLong() are provided because they are considerably faster than Sun’s methods for accomplishing the same tasks, and easier to use.
A developer new to ZAppSvr can run into a few issues. Here are a few common answers:
If my service is not HTTP, how do I use ZAppSvr?
ZAppSvr is a request-response server, and while it can be used to easily create and manage HTTP based web services, the advantages of ZAppSvr extend well beyond HTTP and web pages. There is no strict enforcement of HTTP protocol, which means the request data arrives at your Plugin as it was sent, and you can do whatever you want to do in your application and return any data you choose. This creates an open environment that allows you great flexibility.
Let's say you wanted to send an encrypted message to ZAppSvr, and get an answer the was also encoded. You can use the HTTP POST protocol to send a binary packet of data to ZAppSvr using the command POST (i.e. myMessage.enc) in HTTP the post will be processed and expects a length encoded block of binary data. Your Plugin would decrypt the message, encrypt the response, and reply with a length-encoded reply. Only the "myMessage.enc" request would be visible in the packet.
Your application would not be a browser in this case, and would receive the data in response to the query and decrypt the encoded message for the user.
The fact is that except for the request definitions (GET, POST) you can define your own protocol to accomplish anything you want by using the headers, request, and POST binary encoding options. You can accomplish anything you want with ZAppSvr.
The benefits to this methodology are:
Why do I keep getting 404 returned on every request?
Probably the most common problem you can have is failing to assign the new byte[] data that you want to return to the requestor to o[7]. This will result in a 404, File Not Found error. If your byte[] is returned empty, the request is automatically sent to appropriate web server target. The 404 error is returned to the user from the web server.
Why is my Plugin not working?
This error is usually caused by not adding the proper filter to the list found in Options->Plugin Process List Config. If you wanted to process all html requests, you would put *.htm* in the list. You could also limit processing to a specific request. See the configuration documentation for more details.
What's the Target in Configuration?
The target server is the web server where you are going to store web content. It can be local or somewhere else. It’s up to you. If you want to load balance you will have a list of servers for the load balancer to choose from. | http://zeropoint.com/Support/ZAppSvr/ZAppSvrApplicationProgramming.html | CC-MAIN-2017-39 | refinedweb | 1,735 | 51.99 |
Problem Statement
We are given a matrix of all the integers. The problem “Find distinct elements common to all rows of a matrix” asks to find out all the possible distinct elements but common in each of the rows present in a matrix.
Example
arr[]={ {11, 12, 3, 10}, {11, 5, 8, 3}, {7, 11, 3, 10}, {9, 10, 11, 3}}
3 11
Explanation: 3 and 11 are the two numbers that are distinct and also common in each of the rows in a given matrix.
Algorithm to find distinct elements common to all rows of a matrix
1. Declare a Set “SETValue”. 2. Add all the values of the first row of a matrix into the “SETValue”. 3. Traverse the matrix from the second row of a given matrix. 1. Declare a new set let’s say “temp”, every time for each row of a matrix. 1. Add all the values of that particular row in “temp” Set. 2. Iterate over the set “SETValue” in which we stored our first row values. 1. Check if temp contains any of the value of SETValue. 1. If it contains, then removes that value from the SETValue. 3. If SETValue size is equal to 0, then break the loop. 4. Traverse SETValue and print all the values in it.
Explanation
Given a matrix of integers. Our task is to find out all the possible values of a matrix that are distinct to each other. And also common in each of the rows in a matrix. We will be using the Set Data Structure in solving this question. This Set Data Structure helps in removing or not accepting the copied elements. We will be traversing the matrix from the second row of the matrix. Because the first row we will be already assigned to a Set.
We will declare a Set first called SETValue and add all the values of a matrix’s first row into the set. This is just because we have to check all the elements that they should be common in all of the rows. So we can use the first row that will be assigned to a Set as a reference.
We will be traversing the matrix now from the second-row elements because we have already covered the first row and now from the second row we will be taking a new Set Data structure, in fact, we will be taking new Data Structure for each new row of a given matrix in the traversal. Because we have to store those particular row elements into the new Set called “temp”. Then we are going to check if any of the value of SETValue is present in temp if present then we are going to remove that element. Also, we have put one condition there to check the null pointer exception value. If the size of the SETValue set will become 0, then it will break the loop and there will be no runtime error.
As we are removing the elements from SETValue, we have an output value in there after the traversal, so we will be printing those values.
Code
C++ code to find distinct elements common to all rows of a matrix
#include<unordered_set> #include<iostream> using namespace std; const int MAX = 100; void getDistinctCommonElements (int mat[][MAX], int n) { unordered_set<int> SETValue; for (int i=0; i<n; i++) SETValue.insert(mat[0][i]); for (int i=1; i<n; i++) { unordered_set<int> temp; for (int j=0; j<n; j++) temp.insert(mat[i][j]); unordered_set<int>:: iterator itr; for (itr=SETValue.begin(); itr!=SETValue.end(); itr++) if (temp.find(*itr) == temp.end()) SETValue.erase(*itr); if (SETValue.size() == 0) break; } unordered_set<int>:: iterator itr; for (itr=SETValue.begin(); itr!=SETValue.end(); itr++) cout << *itr << " "; } int main() { int mat[][MAX] = { {11, 12, 3, 10}, {11, 5, 8, 3}, {7, 11, 3, 1}, {9, 0, 11, 3} }; int n = 4; getDistinctCommonElements (mat, n); return 0; }
3 11
Java code to find distinct elements common to all rows of a matrix
import java.util.HashSet; import java.util.Iterator; import java.util.LinkedList; import java.util.Collection; class DistinctCommonElements { public static void getDistinctCommonElements(int mat[][], int n) { Collection<Integer> removeElements = new LinkedList<Integer>(); HashSet<Integer> SETValue=new HashSet<>(); for (int i=0; i<n; i++) SETValue.add(mat[0][i]); for (int i=1; i<n; i++) { HashSet<Integer> temp= new HashSet<Integer>(); for (int j=0; j<n; j++) temp.add(mat[i][j]); for(Integer element : SETValue) if(!(temp.contains(element))) removeElements.add(element); SETValue.removeAll(removeElements); if (SETValue.size() == 0) break; } Iterator<Integer> itr=SETValue.iterator(); while(itr.hasNext()) System.out.print(itr.next()+" "); } public static void main(String [] args) { int mat[][] = { {11, 12, 3, 10}, {11, 5, 8, 3}, {7, 11, 3, 10}, {9, 10, 11, 3} }; int n = 4; getDistinctCommonElements (mat, n); } }
3 11
Complexity Analysis
Time Complexity
Here we have been using two nested loops and using unordered_set/HashSet gave us polynomial time complexity. O(n2) where “n” is the size of the matrix.
Space Complexity
O(n) where “n” is the size of the matrix, for storing the input and storing elements in HashSet. | https://www.tutorialcup.com/interview/hashing/find-distinct-elements-common-to-all-rows-of-a-matrix.htm | CC-MAIN-2021-04 | refinedweb | 865 | 63.59 |
The Realm Data Model
At the heart of the Realm Mobile Platform is the Realm Mobile Database, an open source, embedded database library optimized for mobile use. If you’ve used a data store like SQLite or Core Data, at first glance the Realm Mobile Mobile concepts being discussed are cross-platform; simple examples will be given in Swift. Consult the documentation section for your preferred binding for examples in your language.
What is a Realm?
A Realm is an instance of a Realm Mobile Database container. Realms can be local, synchronized, or in-memory. In practice, your application works with any kind of Realm the same way. In-memory Realms have no persistence mechanism, and are meant for temporary storage.–so the Realm could represent a channel in a chat application, for instance, being updated by any user talking in that channel. Or, it could be a shopping cart, accessible only to devices owned by you.
If you’re used to working with other kinds of databases, here are some things that a Realm is not:
- A Realm is not a single application-wide database. While an application generally only uses one SQL database, an application often uses multiples Realms to organize data more efficiently, or to “silo” data for access control purposes.
- A Realm is not a table. Tables typically only store one kind of information: user records, email messages, and so on. But a Realm can contain multiple kinds of objects.
- A Realm is not a schemaless document store. Because object properties are analogous to key/value pairs, it’s easy to think of a Realm as a document store, but objects in a Realm have defined schemas that support giving values defaults or marking them as required or optional.
The hypothetical chat application above might use one synchronized Realm for public chats, another synchronized Realm storing user data, yet another synchronized Realm for a “master channel list” that’s read-only to non-administrative users, and a local Realm for persisted settings on that device. Or a multi-user application on the same device could store each user’s private data in a user-specific Realm. Realms are lightweight, and your applicaion can be using several at one time. (On mobile platforms, there are some resource constraints, but up to a dozen open at once should be no issue.)
Opening a Realm
In JavaScript, the schema for your model must be passed into the constructor as part of the configuration object. See Models in the JavaScript documentation for details.
When you open a Realm, you pass the constructor a configuration object that defines how to access it. The configuration object specifies where the Realm database is located:
- a path on the device’s local file system
- a URL to a Realm Object Server, with appropriate access credentials (user/password, authentication token)
- an identifier for an in-memory Realm
(The configuration object may specify other values, depending on your language, and is usually used for migrations when those are necessary. As noted above, the configuration object also includes the model schema in JavaScript.) If you don’t provide a configuration object, you’ll open the default Realm, which is a local Realm specific to that application.
Opening a synchronized Realm, therefore, might look like this. For this example, we’ll assume the Realm is named
"settings".
// create a configuration object let realmUrl = URL(string: "realms://example.com:9000/~/settings")! let realmUser = SyncCredentials.usernamePassword(username: username, password: password) let config = Realm.Configuration(user: realmUser, realmURL: realmUrl) // open the Realm with the configuration object let settingsRealm = try! Realm(configuration: config)
Opening a local or in-memory Realm is even simpler—it doesn’t need a URL or user argument–and opening the default Realm is just one line:
let defaultRealm = try! Realm()
Realm URLs
Synchronized Realms may be public, private, or shared. They’re all accessed the same way—on a low level, there’s no difference between them at all. The difference between them is access controls, which users can read and write to them. The URL format may also look a little different:
- A public Realm can be accessed by all users. Public realms are owned by the admin user on the Realm Object Server, and are read-only to non-admins. These Realms have URLs of the form
realms://server/realm-name.
- A private Realm is created and owned by a user, and by default only that user has read and write permissions for it. Private Realms have URLs of the form
realms://server/user-id/realm-name.
- A shared Realm is a private Realm whose owner has granted other users read (and possibly write) access—for instance, a shopping list shared by multiple family members. It has the same URL format as a private Realm (
realms://server/user-id/realm-name); the
user-idsegment of the path is the ID of the owning user. Sharing users all have their own local copies of the Realm, but there’s only one “master” copy synced through the Object Server.
Very often in private Realm URLs, you’ll see a tilde (
~) in place of the user ID; this is a shorthand for “fill in the current user’s ID.” This makes it easier for application developers to refer to private Realms in code: you can simply refer to a private settings Realm, for example, with
realms://server/~/settings.
You can think of Realm URLs as matching a file system: public Realms live at the top-level “root” directory, with user-owned Realms in subdirectories underneath. (The tilde was chosen to match the Unix style of referring to a user’s home directory with
~.)
Note: the
realms:// prefix is analogous to
https://, e.g., the “s” indicates the use of SSL encryption. A Realm URL beginning with
realm:// is unencrypted.
Permissions
Realms managed by the Realm Object Server have access permissions that control whether it’s public, private, or shared. Permissions are set on each Realm using three boolean flags:
- The
mayReadflag indicates a user can read from the Realm.
- The
mayWriteflag indicates a user can write to the Realm.
- The
mayManageflag indicates a user can change permissions on the Realm for other users.
The permission flags can be set on a default basis and a per-user basis. When a user requests access for a Realm, first the private: the owner has all permissions on it, and no other user has any permissions for it. Other users must be explicitly granted access. (Admin users, though, are always granted all permissions to all Realms on the Object Server.)
For more details about permissions, see:
- Authorization for the Realm Object Server
- Access Control for your language SDK:
Models and Schema
To store an object in a traditional relational database, the object’s class (say,
User) corresponds to a table (
users), with each object instance being mapped to a table row and the object’s properties mapping to table columns. In Realm, though, your code works with the actual objects.
class Dog: Object { dynamic var name = "" dynamic var age = 0 dynamic var breed: String? = nil dynamic var owner: Person? }
Our
Dog object has four properties, two of which are required and have default values (
name, with a default of the empty string, and
age, with a default of
0). The
breed property is an optional string, and the
owner property is an optional
Person object. (We’ll get to that.) Optional properties are sometimes called nullable properties by Realm, meaning that their values can be set to
nil (or
null, depending on your language). Optional properties don’t have to be set on objects to be stored in a Realm. Required properties, like
name and
age, cannot be set to
nil.
Check your language SDK for the proper syntax for required and optional properties! In Java, all properties are nullable by default, and required properties must be given the
@Required notation. JavaScript marks property types and default values in a different fashion.
Relations
In relational databases, relations between tables are defined with primary keys and foreign keys. If one or more
Dogs can be owned by one
Person, then the
Dog model will have a foreign key field that contains the primary key of the
Person who owns them. This can be described as a “has-many” relationship: a
Person has-many Dogs. The inverse relationship,
Dog belongs-to Person, isn’t explicitly defined in the database, although some ORMs implement it.
Realm has similar relationship concepts, declared with properties in your model schema.
To-One Relations
Let’s revisit the
Dog model above:
class Dog: Object { dynamic var name = "" dynamic var age = 0 dynamic var breed: String? = nil dynamic var owner: Person? }
The
owner property is the
Object subclass you want to establish a relationship with. This is all you need to define a “to-one” relationship (which could be either one-to-one or many-to-one). Now, you can define a relationship between a
Dog and a
Person:
let bob = Person() let fido = Dog() fido.owner = bob
This is similar in other languages. Here’s the Java implementation of
Dog:
public class Dog extends Realm Object { @Required private String name = ""; @Required private Integer age = 0; private String breed; private Person owner; }
To-Many Relationships
Let’s show the matching
Person class for
Dog:
class Person: Object { let name = "" let dogs = List<Dog>() }
A list in Realm contains one or more Realm objects. To add Fido to Bob’s list of dogs:
bob.dogs.append(fido)
Again, this is similar in other languages; in Java, you use
RealmList as the property type (to distinguish them from native Java lists):
public class Person extends RealmObject { @Required private String name; private RealmList<Dog> dogs;
(Note that in Java,
RealmList properties are always considered required, so they don’t need the
@Required notation. JavaScript defines list properties in a different fashion. As always, consult the documentation and API reference for your language SDKs for specifics.)
Inverse Relationships
You’ll note that defining the
Person has-many Dogs relationship didn’t automatically create a
Dog belongs-to Person relationship; both sides of the relationship need to be set explicitly. Adding a
Dog to a
Person’s
dogs list doesn’t automatically set the dog’s
owner property. It’s important to define both sides of this relationship: while it makes it easier for your code to traverse relationships, it’s also necessary for Realm’s notification system to work properly.
Some Realm language bindings provide “linking objects” properties, which return all objects that link to a given object from a specific property. To define
Dog this way, our model could be:
class Dog: Object { dynamic var name = "" dynamic var age = 0 dynamic var breed: String? = nil let owners = LinkingObjects(fromType: Person.self, property: "dogs") }
Now, when we execute
bob.dogs.append(fido), then
fido.owner will point to
bob.
Currently, Objective-C, Swift, and Xamarin provide linking objects.
Primary Keys
While Realm doesn’t have foreign keys, it does support primary key properties on Realm objects. Declaring one of the properties on a model class to be a primary key enforces uniqueness: only one object of that class with the same primary key can be added to a Realm. Primary keys are also implicit indexes: querying an object on its primary key is extremely efficient.
For details about how to specify a primary key, consult your language SDK’s documentation:
Indexes
Adding an index to a property significantly speeds up some queries. If you’re frequently making an equality comparison on a property—that is, retrieving an object with an exact match, like an email address—adding an index may be a good idea. Indexes also speed up exact matches with “contains” operators (e.g.,
name IN {'Bob', 'Agatha', 'Fred'}).
Consult your language SDK for information on how to set indexes:
Migrations
Since data models in Realm are defined as standard classes, making model changes is very easy. Suppose you had a
Person model which contained these properties:
class Person: Object { dynamic var firstName = "" dynamic var lastName = "" dynamic var age = 0 }
And you wished to combine the
firstName and
lastName properties into a single
name property. The model change is simple:
class Person: Object { dynamic var name = "" dynamic var age = 0 }
However, now the schema in the Realm file doesn’t match your model—when you try to use the existing Realm, errors will happen. To fix this, you’ll need to perform a migration—essentially, call a small bit of code in your application which can detect the old version of the Realm schema and upgrade it on disk.
Migrations With Local Realms
The specifics of how to perform a migration vary from language to language, but the basics are always similar:
- When you open the Realm, a schema version and migration function are passed to the constructor in the configuration object.
- If the existing schema version is equal to the schema version passed to the constructor, things proceed as normal (no migration is performed).
- If the existing schema version is less than the schema version passed to the constructor, the migration function is called.
In Swift, a migration function added to the configuration object might look like this.
let config = Realm.Configuration( schemaVersion: 1, migrationBlock: { migration, oldSchemaVersion in if (oldSchemaVersion < 1) { migration.enumerateObjects(ofType: Person.className()) { oldObject, newObject in let firstName = oldObject!["firstName"] as! String let lastName = oldObject!["lastName"] as! String newObject!["name"] = "\(firstName) \(lastName)" } } })
If no version is specified for a schema, it defaults to
0.
Migrations With Synced Realms
If a Realm is synced, the rules for performing migrations are a little different.
- functions).
If you can’t use a custom migration function, how do you make schema changes like the previous example on a synced Realm? There are two ways to do it:
- On the client side, you can write a notification handler that performs the changes.
- On the server side, you can write a Node.js function that performs them.
Neither of these will allow you to apply destructive changes to an existing Realm. Instead of doing that, create a new synced Realm with the new schema, then create a function which listens for changes on the old Realm and copies values to the new one. This can happen on either the client or server side.
More about Migrations
To see examples and more details in your preferred language binding, consult the language-specific documentation for migrations: | https://realm.io/jp/docs/data-model/ | CC-MAIN-2018-34 | refinedweb | 2,410 | 53.41 |
MVar
If you're looking for the latest 3.x click here! two fundamental (atomic) operations:
put: fills the
MVarif it is empty, or blocks (asynchronously) if the
MVaris full, until the given value is next in line to be consumed on
take
take: tries reading the current value, or blocks (asynchronously) until there is a value available, at which point the operation resorts to a
takefollowed by a
put
An additional but non-atomic operation is
read, which tries reading the
current value, or blocks (asynchronously) until there is a value available,
at which point the operation resorts to a
take followed by a
put..
Use-case: Synchronized Mutable Variables
import monix.execution.CancelableFuture import monix.eval.{MVar, Task} def sum(state: MVar[Int], list: List[Int]): Task[Int] = list match { case Nil => state.take case x :: xs => state.take.flatMap { current => state.put(current + x).flatMap(_ => sum(state, xs)) } } val state = MVar(0) val task = sum(state, (0 until 100).toList) // Evaluate val f: CancelableFuture[Int] = task.runAsync { private[this] val mvar = MVar(()) def acquire: Task[Unit] = mvar.take def release: Task[Unit] = mvar.put(()) def greenLight[A](fa: Task[A]): Task[A] = for { _ <- acquire a <- fa.doOnCancel(release) _ <- release } yield a }
And now we can apply synchronization to the previous example:
val lock = new MLock val state = MVar(0) val task = sum(state, (0 until 100).toList) val atomicTask = lock.greenLight(task) // Evaluate val f: CancelableFuture[Int] = atomicTask.runAsync channel = MVar.empty[Option[Int]] val count = 100000 val producerTask = producer(channel, (0 until count).toList).executeWithFork val consumerTask = consumer(channel, 0L).executeWithFork // Ensure they run in parallel, not really necessary, just for kicks val sumTask = Task.mapBoth(producerTask, consumerTask)((_,sum) => sum) // Evaluate val f: CancelableFuture[Long] = sumTask.runAsync
Running this will work as expected. Our
producer pushes values
into our
MVar and our
consumer will consume all of those values. | https://monix.io/docs/2x/eval/mvar.html | CC-MAIN-2019-51 | refinedweb | 317 | 51.55 |
Monday, June 29, 2009
Sunday, June 28, 2009
Thursday, June 25, 2009
ssh
Posted by Steven Ness at 6/25/2009 10:31:00 AM
shell
Change the default login shell on Mac OS X.
Posted by Steven Ness at 6/25/2009 10:02:00 AM
text
Online Text Utilities
Things like "Encode URI" and "UTF-8 Decode". Could be useful.
big O
A Beginners? Guide to Big O Notation
Good article, but kinda fades out towards the end.
Wednesday, June 24, 2009
theremin
Minimum Theremin Kit Schematic
Theremin Schematics
The Avalon Theremin
The Theremin - By Robert Moog
One Transistor Theremin - Uses an AM radio to pick up the signal
Theremin Schematic
Theremax Schematic
Theremin Construction
Hartley oscillator
Inductor
Capacitor
Electronic Oscillator
LFO - Low-frequency oscillation
Posted by Steven Ness at 6/24/2009 08:39:00 AM
ephesus
Posted by Steven Ness at 6/24/2009 08:35:00 AM
Monday, June 22, 2009
C74 Perspectives: Matt Wright
Wow! Matt used to be a Post-doc at the lab. So cool!
Posted by Steven Ness at 6/22/2009 09:27:00 PM
v8-gl.
Nice.
Posted by Steven Ness at 6/22/2009 09:17:00 AM
ribbon
jQuery Ribbons. Pretty.
Posted by Steven Ness at 6/22/2009 09:16:00 AM
Sunday, June 21, 2009
Saturday, June 20, 2009
Friday, June 19, 2009
c8
Peavey DPM C8. The old MIDI controller in our lab. Quite a beast!
Posted by Steven Ness at 6/19/2009 09:43:00 AM
parrot
Posted by Steven Ness at 6/19/2009 09:39:00 AM
opengl
A bunch of links that I've found useful over the last week while designing MarSndPeek and rewriting the Panning Pedagogy app in OpenGL:
OpenGL Primitives
Simple OpenGL Primitives: Drawing Points, Lines and Polygons with glVertex
QGLWidget Class Reference
Chapter 14 - OpenGL - From the Qt manual
OpenGL & Qt animation
Lesson: 06 - from the awesome nehe OpenGL tutorial
Hello GL Example
glOrtho
Opengl Triangle Tutorial
OpenGL:Tutorials:Tutorial Framework:Light and Fog
fog from nehe
How to use Fog in OpenGL
10 Clipping, Culling, and Visibility Testing
Line and Point antialiasing
Lesson 1 : Viewing Volume & Viewport
Tutorial 08: LookAt - Split - Clipping
GLUT Tutorial : Computing Frames per Second
Some work had been done in Marsyas with OpenGL by Aaron Hechmer, who used to be in George's lab.
Here's a screenshot of the current version of MarSndPeek:
And a screenshot of the OpenGL panning app:
Here's a screenshot of the web based version of the panning app, which you can visit at pan.sness.net
Posted by Steven Ness at 6/19/2009 09:35:00 AM
x11/html
Posted by Steven Ness at 6/19/2009 09:18:00 AM
tty
Posted by Steven Ness at 6/19/2009 09:17:00 AM
Thursday, June 18, 2009
Speaker identification with sndpeek
I'm making a version of this with Marsyas and Qt, it's called MarSndPeek.
cmake wiki
A really nice page on CMake:How To Find Libraries. Very useful.
Posted by Steven Ness at 6/18/2009 02:21:00 PM
qt opengl
A thread suggested that for Re: [CMake] cmake link against Qt4's OpenGL
PROJECT ( COMBINED )
FIND_PACKAGE (Qt4 REQUIRED)
SET(QT_USE_QTOPENGL TRUE)
INCLUDE( ${QT_USE_FILE} )
ADD_EXECUTABLE(exe main.cpp glwidget.cpp window.cpp)
TARGET_LINK_LIBRARIES(exe ${QT_LIBRARIES})
What I found for Marsyas linking a Qt application that uses OpenGL, I first had to add the following lines to marsyas-detect.cmake:
if (WITH_OPENGL)
find_package(OpenGL REQUIRED)
set (MARSYAS_OPENGL 1)
SET(QT_USE_QTOPENGL TRUE)
endif (WITH_OPENGL)
With the important line being
SET(QT_USE_QTOPENGL TRUE)
To get the OpenGL header files to be included I also added the following lines to the CMakeLists.txt file in the directory of the application I was working on:
INCLUDE_DIRECTORIES(${QT_QTOPENGL_INCLUDE_DIR})
Very simple, but really hard to find out how to do.
Posted by Steven Ness at 6/18/2009 11:04:00 AM
cmake opengl
Really nice page about using CMake to compile programs that use OpenGL.
Posted by Steven Ness at 6/18/2009 09:57:00 AM
nethack
Posted by Steven Ness at 6/18/2009 09:08:00 AM
Wednesday, June 17, 2009
as3
Actionscript 3.0 libraries. I wonder how hard it is to integrate these into haXe?
Posted by Steven Ness at 6/17/2009 09:52:00 AM
karmetik
Some new songs by my friend Manj as KarmetiK::Bhutan. It's Live Electroganic Tribal Dance Grooves
Posted by Steven Ness at 6/17/2009 09:21:00 AM
Tuesday, June 16, 2009
shm
Trying to figure out how to turn on SHMConfig in X11 in Ubuntu under VirtualBox in Windows 7 so that I can disable my mouse pointer on my laptop when I'm typing.
Any ideas?
SynapticsTouchpad
xorg.conf & SHMConfig for Synaptics Touchpad
Cannot enable SHMconfig
What happen with SHMConfig?
Touchpad at Wikipedia
How-to disable Touchpad on Linux - for Fedora 7
Posted by Steven Ness at 6/16/2009 06:32:00 PM
Wednesday, June 10, 2009
reinstall grub on ubuntu
sudo grub
find /boot/grub/stage1
root (hd0,0)
setup (hd0)
quit
Posted by Steven Ness at 6/10/2009 07:17:00 PM
Tuesday, June 09, 2009
pan
Check out my new Flash app at pan.sness.net, and as Panning Pedagogy SourceForge.
Posted by Steven Ness at 6/09/2009 08:32:00 PM
hackers
From : Unix turns 40: The past, present and future of a revolutionary OS
Thompson and Ritchie were the consummate "hackers," when that word referred to someone who combined uncommon creativity, brute force intelligence and midnight oil to solve software problems that others barely knew existed.
Nice. Me too.
Posted by Steven Ness at 6/09/2009 01:15:00 PM
melo
celemony melodyne. wow!
Posted by Steven Ness at 6/09/2009 01:02:00 PM
Monday, June 08, 2009
influences
Posted by Steven Ness at 6/08/2009 05:35:00 PM
swf cache
If you have a problem with firefox caching your SWF files try about:config and setting browser.cache.disk.enable to false.
Posted by Steven Ness at 6/08/2009 04:16:00 PM
Sunday, June 07, 2009
Saturday, June 06, 2009
64 RGB-LED color wave table (Arduino, 12x TLC5940)
want make.
Posted by Steven Ness at 6/06/2009 07:15:00 PM
Prototype Solenoid Drumbot - Cocek rhythm
The solenoid version of the drumbot. Much better.
Prototype Stepper/Servo Drumbot
This is a drumbot we're making at the lab!
Friday, June 05, 2009
medline
Posted by Steven Ness at 6/05/2009 03:58:00 PM
Sensitive Fingertips
Posted by Steven Ness at 6/05/2009 02:13:00 PM
Thursday, June 04, 2009
soundex
Soundex is a phonetic algorithm for indexing names by sound, as pronounced in English. The goal is for homophones to be encoded to the same representation so that they can be matched despite minor differences in spelling.
Just what we needed for a recent project. Neat.
Posted by Steven Ness at 6/04/2009 05:12:00 PM
sandy3d
Sandy3d is a fantastic 3d engine for Flash/haXe. I was using it in a recent project, but it turned out I needed too many polygons, and it doesn't seem to be able to use the new 3D accelleration in Flash 10. Still, a really awesome project and nice API.
Sandy FAQ
Sandy API
Posted by Steven Ness at 6/04/2009 04:08:00 PM
maya
Check out this really cool animation by my friend Rafael Besaccia.
Posted by Steven Ness at 6/04/2009 05:34:00 AM
Wednesday, June 03, 2009
resist
An excellent Calculator for Resistor Color Codes
Posted by Steven Ness at 6/03/2009 08:57:00 AM
mysql
The State of MySQL
Interesting that both MySQL and Perl got stuck between versions 5 and 6. Perhaps they should just have jumped to version 7.
That's funny, now that I think of it, CCP4 kind of got stuck between 5 and 6 as well, but it looks like they've leapt now.
The lesson of the day is : Avoid version 6.0.
Posted by Steven Ness at 6/03/2009 07:04:00 AM
jquery
Posted by Steven Ness at 6/03/2009 06:59:00 AM
pd
pd-tutorial
Code examples for "Designing Sound" textbook - uses pd
Pure Data (pd) at wikipedia
Software by Miller Puckette
Crazy pd screenshot
VST - Pd Bridging Plugin
The Theory and Technique of Electronic Music - book by MSP
BodyCoder is a flexible sensor array worn on the body of a performer that sends data generated by movement to an Max/MSP environment via radio.
Products/FMI Workshop
Crazy Max/MSP screenshot
Wild score
Arduino2Max
A Digital Signal Processing Instrument for Improvised Music - Lawrence Casserley
BodyCoder.com
Pd documentation
Graphical Interface for Pure Data
Pd Repertory Project
MSP Publications
MSP bio
Graduate study in computer music at UCSD
Courses taught by Miller Puckette
Make Your Own Music Software with Pure Data
puredata.info
py
Tuesday, June 02, 2009
railgun
Posted by Steven Ness at 6/02/2009 01:30:00 PM
buttons
The Sliding Doors Technique
Recreating the button
button - the forgotten element
Rediscovering the Button Element
How to make sexy buttons with CSS
Creating Funky Forms with CSS
How do I style (css) radio buttons and labels?
Fancy checkboxes and radio buttons
HTML Forms and Input
Styled radio buttons
Styling form controls with CSS, revisited
Posted by Steven Ness at 6/02/2009 11:46:00 AM
yui
YUI Base CSS
Essential, and I can't believe it took me so long to find it!
Posted by Steven Ness at 6/02/2009 11:35:00 AM
liquid
Posted by Steven Ness at 6/02/2009 10:22:00 AM
Monday, June 01, 2009 | http://sness.blogspot.com/2009_06_01_archive.html | CC-MAIN-2014-42 | refinedweb | 1,641 | 60.48 |
Expose 'enum QTextToSpeech::State' in QML
Hi there
I am not so much of a QT/C++ buff. Hence, sorry for struggling with the obvious.
Well, I got stuck trying to react on speech states in QML. Because the emitted
enum QTextToSpeech::Stateis not registered with QML. Please have a look at the snippets below. And most of all, thank you in advance for your hints and helpers!
in main.cpp I have: // load speech module -------------------- QTextToSpeech* speech = new QTextToSpeech; speech->setLocale(QLocale(startLocale)); // load the QML engine -------------------------- QQmlApplicationEngine engine; // making the speech synthesizer class available in QML engine.rootContext()->setContextProperty("speech", speech);
then in main.qml Connections { target: speech onStateChanged: { console.log("current state: changed!"); // stateChange triggers console.log("the state: "+ speech.state); // but the state type is not recognised } }
This produces the following console output: qml: current state: changed! QMetaProperty::read: Unable to handle unregistered datatype 'State' for property 'QTextToSpeech::state'
I figured, I must register the
QTextToSpeech::statein QML. So I added the following line to main.cpp
qmlRegisterUncreatableType<QTextToSpeech::State>("QTextToSpeech", 1, 0, "state", "Error: Class uncreatable");
But that gives the following errors, which are too cryptic for me:
Development/Qt/5.8/clang_64/lib/QtQml.framework/Headers/qqml.h:141: error: no member named 'staticMetaObject' in 'QTextToSpeech::State' QML_GETTYPENAMES ^~~~~~~~~~~~~~~~ Development/Qt/5.8/clang_64/lib/QtQml.framework/Headers/qqml.h:89: expanded from macro 'QML_GETTYPENAMES' const char *className = T::staticMetaObject.className(); \ ~~~^ main.cpp:43: in instantiation of function template specialization 'qmlRegisterUncreatableType<QTextToSpeech::State>' requested here qmlRegisterUncreatableType<QTextToSpeech::State>("QTextToSpeech", 1, 0, "state", "Error: Class uncreatable"); ^
And, if there were no errors in C++, I would add an import statement to main.qml
import QTextToSpeech 1.0
hi there, this is still open for me.
asked another way, does anyone know how to use QTextToSpeech states in QML?
thx a lot
- SGaist Lifetime Qt Champion last edited by
Hi,
IIRC, Q_DECLARE_METATYPE and its friend qRegisterMetaType should be used for that.
The first one to make the enum known to the meta type system and the second one to use it with signals and slots.
Thanks a zillion. For the record:
qtexttospeech.h already has on line 118
Q_DECLARE_METATYPE(QTextToSpeech::State)
Hence, what's missing is the qRegisterMetaType part. Which I am adding in main.cpp before the QTextToSpeech module is loaded.
qRegisterMetaType<QTextToSpeech::State>("State"); QTextToSpeech* speech = new QTextToSpeech;
Then, in main.qml, I am catching the state changed signals and the state like this:
Connections { target: speech onStateChanged: { console.log("speech.state "+ speech.state); if (speech.state == 1){ console.log("--- we are speaking! ---"); } else if (speech.state == 0){ console.log("--- speaking stopped! ---"); } } } | https://forum.qt.io/topic/81100/expose-enum-qtexttospeech-state-in-qml | CC-MAIN-2019-51 | refinedweb | 437 | 53.07 |
my ]
The solution is to recode your CGI to display a "you are logged out" message (which is good form anyway) instead of a redirect. Then you CAN pass the cookie, and all will be right with the world.
Gary Blackburn
Trained Killer
First,.
####.
as you can see, the cookie is the same...
Perhaps the problem is that $in{usr} and $usr
don't match?
THX
Li Tin O've Weedle
mad Tsort's philosopher
my $cache = File::Cache->;new({namespace => 'cookiemaker',
[download]
Should be without ";":
my $cache = File::Cache->new({namespace => 'cookiemaker',
[download]
This probabably happened by copying line 33.
Your servant
Li Tin O've Weedle
mad Tsort's philosopher
Tron
Wargames
Hackers (boo!)
The Net
Antitrust (gahhh!)
Electric dreams (yikes!)
Office Space
Jurassic Park
2001: A Space Odyssey
None of the above, please specify
Results (118 votes),
past polls | http://www.perlmonks.org/index.pl?node_id=72691 | CC-MAIN-2014-35 | refinedweb | 142 | 75.2 |
I am trying to implement an email which will go out when a ticket is over 5 days old (which is what I have set Spiceworks to not re-open the ticket after being closed). I'm new to Liquid and am trying the following:
{% if ticket.status == 'closed' %} {% if {{ '0:0' | date: "%s" | minus: {{ ticket.closed_at | date: "%s" }} }} > 432000 %} Closed over 5 days ago {% else %} Closed 5 or less days ago {% endif %} {% else %} Ticket not closed. {% endif %}
This always lists the ticket as closed 5 of less days ago. What is the correct way to build up the if statement to catch this, as this seems to be where the problem is starting.
4 Replies
This is for Spiceworks "Ticket Notification Template". It triggers when changes to the ticket happen.
In this instance, the ticket would have been closed for over 5 days, and in that instance it may be that no one is aware of the ticket update as it will not re-open. I am, therefore, trying to get it to send an email back to the user saying that the ticket is "dead" and a new one needs to be created.
So the update seems to have messed some things up. Using '0:0' no longer seems to work. Likewise, using "%s" seems to have been removed.
I am trying, therefore, to use:
{% assign current = now | date: "%j" %} {% assign closed = ticket.closed_at | date: "%j" %} {% assign diff = current | minus: closed %} {{% diff %}} {% if ticket.status == 'closed' %} {% if diff >= 6 %} Closed over 5 days ago {% else %} Closed 5 or less days ago {% endif %} {% else %} Ticket not closed. {% endif %}
This results in: Liquid error: comparison of String with 6 failed
Any ideas anyone? | https://community.spiceworks.com/topic/1515746-ticket-notification-template-for-old-closed-tickets | CC-MAIN-2021-39 | refinedweb | 283 | 80.51 |
Maybe I am off, but I thought other classes already cannot inherit from it, because it has
a private constructor.
-----Original Message-----
From: mail@stefan-seelmann.de [mailto:mail@stefan-seelmann.de] On Behalf Of Stefan Seelmann
Sent: Monday, November 22, 2010 7:58 AM
To: Apache Directory Developers List
Subject: Re: Code review - constants in interface
On Mon, Nov 22, 2010 at 2:50 PM, Guillaume Nodet <gnodet@gmail.com> wrote:
> AFAIK, the best pattern for that is to use a final with a private
> constructor and declare public static final fields in it.
>
> public class Constants {
> private Constants() {
> // non-instantiable class
> }
>
> public static final String TYPE = "type";
> }
Sounds good. One additional improvement would be to declare the class
as final, just to avoid that other classes inherit from it.
Kind Regards,
Stefan | http://mail-archives.apache.org/mod_mbox/directory-dev/201011.mbox/%3CD97933926A67E94DAC10D51E2011C29D3EA68CA74A@CRPMBOXPRD03.polycom.com%3E | CC-MAIN-2016-26 | refinedweb | 134 | 53.81 |
Package: glibc Version: 2.3.1-16 Severity: normal glob() is busted in glibc because it does not correctly handle the situation where a symlink is part of a path. For example: There exists a symlink: /data/a -> /data1/a /data1/a is a directory which contains: abc def xyz A glob() call using the pattern: /data/*/* will fail. This is because around line 1373 of glob.c there exists the following code: ------- #ifdef HAVE_D_TYPE /* If we shall match only directories use the information provided by the dirent call if possible. */ if ((flags & GLOB_ONLYDIR) && d->d_type != DT_UNKNOWN && d->d_type != DT_DIR) continue; #endif ------- When a path element is a symlink the d_type for it is DT_LINK. DT_LINK should probably be added to the statement above as another valid type. Of course, another check will need to be made if you want to be sure the symlink points to a directory. This check should probably work on any type of file and be outside the #ifdef above so that GLOB_ONLYDIR will work when HAVE_D_TYPE isn't defined (as I read it this isn't the case currently). Stephen
Attachment:
pgp7EjInSJALa.pgp
Description: PGP signature | http://lists.debian.org/debian-glibc/2003/04/msg00188.html | CC-MAIN-2013-48 | refinedweb | 192 | 64.71 |
capng_set_caps_fd man page
capng_set_caps_fd —
Synopsis
#include <cap-ng.h>
int capng_set_caps_fd(int fd);
Description
This function will write the file based capabilities to the extended attributes of the file that the descriptor was opened against. The bounding set is not included in file based capabilities operations. Note that this function will only work if compiled on a kernel that supports file based capabilities such as 2.6.2 6 and later.
Return Value
This returns 0 on success and -1 on failure.
See Also
capng_get_caps_fd(3), capabilities(7)
Author
Steve Grubb
Referenced By
capng_get_caps_fd(3).
June 2009 Red Hat Libcap-ng API | https://www.mankier.com/3/capng_set_caps_fd | CC-MAIN-2017-47 | refinedweb | 102 | 51.24 |
1.10: Public Access Specifiers
- Page ID
- 34642:
// C++ program to demonstrate public // access modifier #include<iostream> using namespace std; // class definition class Circle { public: double radius; double compute_area() { return 3.14*radius*radius; } }; // main function int main() { Circle obj; // accessing public datamember outside class obj.radius = 5.5; cout << "Radius is: " << obj.radius << "\n"; cout << "Area is: " << obj.compute_area(); return 0; }
Output:
Radius is: 5.5 Area is: 94.985
In the above program the data member radius is public so we are allowed to access it outside the class.
Adapted from:
"C++ Classes and Objects" by Abhirav Kariya, Geeks for Geeks is licensed under CC BY 4.0 | https://eng.libretexts.org/Courses/Delta_College/C_-_Data_Structures/01%3A_OOP_Concepts/1.10%3A_Public_Access_Specifiers | CC-MAIN-2021-17 | refinedweb | 110 | 58.99 |
I am using MVC5 & EF6. I am doing code-first approach. I have some tables that require to be generated using migration (works) and some tables that I need to use from existing database - tables.
in the DbContext class I have
'new table that is created in the DB (works) public DbSet<Subscription> Subscriptions { get; set; } public DbSet<Memeber> Members { get; set; } 'existing table. public DbSet<CodeTable> CodeTable { get; set; }
in the Configuration- (Migration folder)
public Configuration() { AutomaticMigrationsEnabled = true; }
what it does now, it creates a new table called CodeTables
Update-Database -Verbose -Force (That doesnt do anything)
Using StartUp project 'Test'.
Using NuGet project 'Test'.
Specify the '-Verbose' flag to view the SQL statements being applied to the target database.
Target database is: 'TESTDB' (DataSource: 10.10.50.89, Provider:
System.Data.SqlClient, Origin: Configuration).
No pending explicit migrations.
Running Seed method.
and then run the application, I get an exception
System.Data.SqlClient.SqlException (0x80131904): Invalid object name 'dbo.Members'. at System.Data.SqlClient.SqlConnection.OnError(SqlException exception
because the table not found. Table does not get generated.
How do I let it know that if table not found. Create it?
I noticed if I delete __MigrationHistory and then run the Update-Database. It then complains about my other tables that exists
There is already an object named 'Subscriptions' in the database.
and it only works if I delete all my tables. But this seems to be silly, deleting all tables. I hope there is another approach.
To use code first with an existing database you need to do two things: 1) specify your connection string and 2) turn off the database initialization strategy. Those two things can be achieved with the following context sample:
public class ApplicationDbContext : DbContext { public ApplicationDbContext() : base("ConnectionStringName") { Database.SetInitializer<ApplicationDbContext>(null); } // DbSets here }
Now, by convention, Entity Framework assumes your table names are pluralized forms of the entity class name. If the table name is not plural and/or it is not the same as the entity class name, then you can use the
Table attribute to specify exactly what it should be:
[Table("foo_table")] public class Foo { // properties }
Likewise, if your column names do not match up with your property names, you can use the
Column attribute to specify those:
[Column("strFoo")] public string Foo { get; set; }
UPDATE
On first reading, I didn't pay attention to the fact that you're trying to mix and match existing tables with tables generated by code first. You cannot do this. Since using an existing database/existing tables requires disabling the initialization strategy, either all the tables in that database must be existing or Entity Framework must generate all the tables. You can't go halfway.
If you need to utilize some existing tables and have EF create some, you need two databases and two contexts, one where EF will generate everything via code first, and another where the initialization strategy is off and you're responsible for the database and tables. Importantly, this means you can not mix and match these. All your code first entities can not reference any of your existing database entities via navigation properties, or they will be implicitly added to the code first context and EF will generate the tables.
The best you can do is to have a regular property that holds the id of the related entity, and then manually use this id to look up the entity from the existing database context. In other words, it will not be a true foreign key, and you will not be able to utilize lazy-loading, etc.
I do it differently - I create one large context with ALL tables I will ever need - and do migrations/DB updates on that context. And then create several "read-only" contexts - in the sense that I call
Database.SetInitializer(null) - meaning they will not have migrations etc - and add only necessary
DbSet there. This way I can achieve exactly what you are describing. | https://entityframeworkcore.com/knowledge-base/35606077/ef-using-code-first-with-existing-table | CC-MAIN-2022-40 | refinedweb | 663 | 54.73 |
Week.
Game Play
We’ve got laser and fireball shooting, plus a basic AI for the cat enemies in place. Brass Monkey support is now in the game too; you can fly around the environment by tilting your phone and using the touch screen of that device to shoot and fly. You should definitely try it out by grabbing the Brass Monkey app for Android or iOS and loading up the latest demo of the game.
We did some early playtesting with attendees at the MassDigi Game Challenge at Microsoft’s NERD Center this weekend. People found the controls to be intuitive, and the early version of the game fun. The main complaint was how hard it was to shoot the cats. Luckily we believe that eye tracking, a well designed target reticle, and better hit detection will solve a lot of these issues.
Levano Ultrabook As a Gaming Device
What we’ve been finding is that playing the game with Brass Monkey controls with the Yoga Ultrabook flipped so the keyboard isn’t usable really works well. The form factor of the convertible Ultrabook plus its weight and graphics capabilities really make for an excellent gaming system, and when flipping it around like this it gives the feeling of a dedicated arcade machine. This effect is going to be even more pronounced once we incorporate the head tracking features.
Face Tracking
Our endeavors into face tracking this week haven’t been without their challenges. Since we’re dealing with the C# ports of C++ libraries (for both the OpenCV libraries and the Intel Perceptual Computing SDK), we had quite a few issues with the documentation not matching the classes and with Unity parsing the DLLs correctly. By Friday we had decided to ditch the Unity Port of the Intel Perceptual Computing SDK all together. The nail in the coffin was when Unity incorrectly threw a compile error on one of OpenCV core data types because a private variable was declared in the serialized parent and the inheriting class (Unity essentially thought a local variable was being declared twice). We are now going to write what we need in C++ using OpenCV and the depth data directly, and create a DLL to be loaded into Unity with the methods we need exposed there. We’ve decided to also publish what we come up with as an Open Source Library once the competition is complete. We are taking inspiration for this from Open Kinect. A robust community like that will really help stoke the fire for other developers to create applications using Intel’s Perceptual Computing technology.
Speaking of Open Connect, we got thinking based on this library, that one huge limitation with the Intel SDK is that it only runs on Windows. It would be very beneficial to have a library that bridges the gap to the other operating systems as well. According to Bob Duffy at Intel “Mac and Linux support are desired, but not yet official”. We will be doing a ton of refinement on head tracking and eye tracking features and making it easier for Unity developers to work with the Perceptual Computing Camera with our library. Perhaps what we end up publishing can be incorporated directly into Intel’s library, and we will all have better tools moving forward.
There were lots of people on Intel’s forum trying to figure out the UV mappings in Unity, and it doesn’t seem that anyone has yet figured this out. Our version does work, but we’ve found that it has a ton of limitations and would need smoothing to be super accurate.
For those of you that are having trouble with mapping the depth sensor data with the RGB data in in Unity we offer you this code (in C#) for now:
using UnityEngine; using System; using System.Runtime.InteropServices; using OpenCvSharp; public class TexturePlayback:MonoBehaviour { private const float HIGH_PASS = 1000.0f;//825.0f; private const float LOW_PASS = 0.0f;//625.0f; private Texture2D rgbTexture; private PXCUPipeline pp; private int[] depthMapSize = new int[2]{0,0}; private int[] RGBMapSize = new int[2]{0,0}; private int[] uvMapSize = new int[2]{0,0}; private PXCUPipeline.Mode mode = PXCUPipeline.Mode.DEPTH_QVGA | PXCUPipeline.Mode.COLOR_VGA; void Start() { pp = new PXCUPipeline(); if (!pp.Init(mode)) { print("Unable to initialize the PXCUPipeline"); return; } pp.QueryRGBSize(RGBMapSize); if (RGBMapSize[0] > 0) { print("rgb map size: width = " + RGBMapSize[0] + ", height = " + RGBMapSize[1]); rgbTexture = new Texture2D (RGBMapSize[0], RGBMapSize[1], TextureFormat.ARGB32, false); // use the rgb texture as the rendered texture renderer.material.mainTexture = rgbTexture; pp.QueryDepthMapSize(depthMapSize); if (depthMapSize[0] > 0) { print("depth map size: width = " + depthMapSize[0] + ", height = " + depthMapSize[1]); } pp.QueryUVMapSize(uvMapSize); if (uvMapSize[0] > 0) { print("uv map size: width = " + uvMapSize[0] + ", height = " + uvMapSize[1]); } } } void OnDisable() { pp.Close(); pp.Dispose(); } void Update() { if (!pp.AcquireFrame(false)) return; bool textureUpdated = false; if (pp.QueryRGB(rgbTexture)) { textureUpdated = true; } // only attempt the following if we have a depth map with uvs if (depthMapSize[0] > 0 && uvMapSize[0] > 0) { short[] depthStorage = new short[depthMapSize[0] * depthMapSize[1]]; //IplImage mask = Cv.CreateImage(new CvSize(depthMapSize[0], depthMapSize[1]), BitDepth.U8, 3); float[] uvStorage = new float[uvMapSize[0] * uvMapSize[1] * 2]; if (pp.QueryDepthMap(depthStorage) && pp.QueryUVMap(uvStorage)) { //float range = HIGH_PASS - LOW_PASS; DepthData[] depthData = new DepthData[depthMapSize[0] * depthMapSize[1]]; for (int r = 0; r < depthData.Length; r++) { depthData[r] = new DepthData(); } // create a depth data map that has been corrected to match the RGB x,y positions for (int y = 0; y < depthMapSize[1]; y++) { for (int x = 0; x < depthMapSize[0]; x++) { int currentIndex = y * depthMapSize[0] + x; //float rawDepthData = depthStorage[currentIndex]; //float depthColor = 0.0f; // make sure we don't go out of range // find the new x and y for 640x480 color map using the uvs and scale back to 320x240 int xx = (int)((uvStorage[currentIndex * 2 + 0] * depthMapSize[0])); int yy = (int)((uvStorage[currentIndex * 2 + 1] * depthMapSize[1])); if (xx >= 0 && xx < depthMapSize[0] && yy >= 0 && yy < depthMapSize[1]) { int newIndex = yy * depthMapSize[0] + xx; //if (rawDepthData < HIGH_PASS && rawDepthData > LOW_PASS) // depthColor = (HIGH_PASS - rawDepthData) / range; //depthData[newIndex] = new Color(depthColor, depthColor, depthColor, 1.0f); depthData[newIndex].rawDepth = depthStorage[currentIndex]; } } } // TODO smooth the depth data // set the mask on the rgb data Color[] rgbColors = rgbTexture.GetPixels(); for (int y = 0; y < rgbTexture.height; y++) { for (int x = 0; x < rgbTexture.width; x++) { int currentIndex = y * rgbTexture.width + x; // look back into the depth data for each pixel int depthIndex = (y / 2) * depthMapSize[0] + (x / 2); // change the color based on the results from the high pass filter if (depthData[depthIndex].rawDepth > HIGH_PASS) { rgbColors[currentIndex] = new Color(1, 1, 1, 1); } } } // set the new pixels on the texture rgbTexture.SetPixels(rgbColors); // mark the texture as updated textureUpdated = true; } } // if we have had an update, apply it to the material // we want Texture.Apply to be called as few times as possible since it is very expensive if (textureUpdated) rgbTexture.Apply(); pp.ReleaseFrame(); } void SetColor(Texture2D texture, Color color, bool applyInstantly = false) { Color[] rgbColors = texture.GetPixels(); for (int y = 0; y < texture.height; y++) { for (int x = 0; x < texture.width; x++) { rgbColors[y * texture.width + x] = color; } } texture.SetPixels(rgbColors); if (applyInstantly) texture.Apply(); } }
Here is a quick video displaying the above code:
The moment when light struck our brains came on line 069 - multiplying the size of the UV Storage array by 2. Even though the uv map resolution is the same as the Depth Data, you need to double it to account for the x AND y coordinates needed for mapping per pixel. We lost some hours on that (why return a specific UV Map size in QueryUVMapSize that needs to be doubled? Are you angry with us?)
Detailed Field of View specs for the RBG + Depth camera are not provided by Intel (just one spec for Diagonal FOV). With Open Kinect’s API and specs pages, they give you diagonal, vertical, and horizontal FOV, which is nice to have for estimating the size of objects in video streams (rather than doing a full camera calibration via OpenCV). This is something that Intel should provide out of the box. In the future you will be able to use our code (for this make & model camera).
Eye Tracking Eigen Eyes Demo seems too slow. Instead we’ve decided to go with Haar Cascade of eye images to grab the eyes region, then we will use another algorithm to detect exact pupil movement. We have had fun this week playing with all of the Haar Cascades that ship with OpenCV (mouth, frontal face, profile face, mouth, pretty comprehensive; we’re very pleased).
Since this is a pretty complex system, and is difficult to describe with just words, we’ve provided a activity diagram with our new approach.
Some Final Thoughts on Perceptual Computing
While going through the process of working with the Intel Perceptual Computing SDK and the Intel Perceptual Computing (IPC) camera we’ve been getting inspired by all the possibilities this technology enables. We mentioned last week how cool it would be to incorporate Google Glass into the mix, but there are some other devices that could offer an interesting future for perceptual computing too. If you’ve not checked out the Leap and Myo do yourself a favor and do so now.
Leap Motion
The Leap takes an interesting approach as a perceptual computing device. It does not include an RGB camera, nor is it mounted like a typical web cam. It instead is designed to sit on your desk and the hand movements and gestures are designed to be detected from the bottom up. This of course means that eye tracking and head tracking aren’t possible, but I like the idea of their setup for hand gestures. The Leap combined with the IPC camera could make for some very interesting applications. I can imagine using the IPC camera for face tracking like we are doing with Kiwi Catapult Revenge, and using the Leap sensor to focus on hand gestures.
Myo
Another approach to perceptual computing and something very, very different is the Myo. This device fits onto your arm as a band that detects the muscle movements that can be boiled down to exact finger movements, wrist rotations and more. The coolest thing about this detection method is that it doesn’t rely on line of site to detect the gestures. Myo combined with Brass Monkey controls would open up all kinds of possibilities. Image what could be done with gun shooting or sword fighting games. You would have the phone in your hand that can trigger the touch screen, and send gyroscope data, plus the muscle events from the Myo. This combined would allow for very fine tuned detection, and you would not need a camera involved at all. Of course adding in a IPC camera would only make the possibilities that much greater. Head and gaze tracking, plus hand movements not in line of site combined with the data from the phone via Brass Monkey just makes our heads spin with the possibilities this would allow. Click to watch a Myo video.
What would you do with these next generation Perceptual Computing gadgets? What ways do you see them working in conjunction with Intel’s offering? We would love to hear your ideas, and of course, as always we welcome your feedback on our progress in the competition. | http://software.intel.com/en-us/blogs/2013/03/04/week-3-title | CC-MAIN-2013-48 | refinedweb | 1,902 | 60.75 |
#include <wx/dialup.h>
This class encapsulates functions dealing with verifying the connection status of the workstation (connected to the Internet via a direct connection, connected through a modem or not connected at all) and to establish this connection if possible/required (i.e.
in the case of the modem).
The program may also wish to be notified about the change in the connection status (for example, to perform some action when the user connects to the network the next time or, on the contrary, to stop receiving data from the net when the user hangs up the modem). For this, you need to use one of the event macros described below.
This class is different from other wxWidgets classes in that there is at most one instance of this class in the program accessed via Create() and you can't create the objects of this class directly.
The following event handler macros redirect the events to member function handlers 'func' with prototypes like:
Event macros for events emitted by this class:
Destructor.
Cancel dialing the number initiated with Dial() with async parameter equal to true.
This function should create and return the object of the platform-specific class derived from wxDialUpManager.
You should delete the pointer when you are done with it.
Dial the given ISP, use username and password to authenticate.
The parameters are only used under Windows currently, for Unix you should use SetConnectCommand() to customize this functions behaviour.
If no nameOfISP is given, the function will select the default one (proposing the user to choose among all connections defined on this machine) and if no username and/or password are given, the function will try to do without them, but will ask the user if really needed.
If async parameter is false, the function waits until the end of dialing and returns true upon successful completion.
If async is true, the function only initiates the connection and returns immediately - the result is reported via events (an event is sent anyhow, but if dialing failed it will be a DISCONNECTED one).
Disable automatic check for connection status change - notice that the
wxEVT_DIALUP_XXX events won't be sent any more neither.
Enable automatic checks for the connection status and sending of
wxEVT_DIALUP_CONNECTED/wxEVT_DIALUP_DISCONNECTED events.
The interval parameter is only for Unix where we do the check manually and specifies how often should we repeat the check (each minute by default). Under Windows, the notification about the change of connection status is sent by the system and so we don't do any polling and this parameter is ignored.
Hang up the currently active dial up connection.
Returns true if the computer has a permanent network connection (i.e.
\ is on a LAN) and so there is no need to use Dial() function to go online.
Returns true if the dialup manager was initialized correctly.
If this function returns false, no other functions will work neither, so it is a good idea to call this function and check its result before calling any other wxDialUpManager methods.
Returns true if the computer is connected to the network: under Windows, this just means that a RAS connection exists, under Unix we check that the "well-known host" (as specified by SetWellKnownHost()) is reachable.
This method is for Unix only.
Sets the commands to start up the network and to hang up again.
Sometimes the built-in logic for determining the online status may fail, so, in general, the user should be allowed to override it.
This function allows to forcefully set the online status - whatever our internal algorithm may think about it.
This method is for Unix only.
Under Unix, the value of well-known host is used to check whether we're connected to the internet. It is unused under Windows, but this function is always safe to call. The default value is
"". | https://docs.wxwidgets.org/3.1.2/classwx_dial_up_manager.html | CC-MAIN-2019-09 | refinedweb | 643 | 51.58 |
Hello geeks and welcome in this article, we will cover NumPy.polyfit(). Along with that, for an overall better understanding, we will look at its syntax and parameter. Then we will see the application of all the theory part through a couple of examples. But at first, let us try to get a brief understanding of the function through its definition.
The function NumPy.polyfit() helps us by finding the least square polynomial fit. This means finding the best fitting curve to a given set of points by minimizing the sum of squares. It takes 3 different inputs from the user, namely X, Y, and the polynomial degree. Here X and Y represent the values that we want to fit on the 2 axes. Up next, let us look at its syntax.
Syntax Of Numpy Polyfit()
numpy.polyfit(x, y, deg, rcond=None, full=False, w=None, cov=False)
Given above is the general syntax of our function NumPy polyfit(). It has 3 compulsory parameters as discussed above and 4 optional ones, affecting the output in their own ways. Next, we will be discussing the various parameters associated with it.
Parameters Of Numpy Polyfit()
1. X:array_like
It represents the set of points to be presented along X-axis.
2. Y:array_like
This parameter represents all sets of points to be represented along the Y-axis.
3. Deg: int
This parameter represents the degree of the fitting polynomial.
4. rcond: float
It is an optional parameter that is responsible for defining a relative number condition of the fit. Singular values smaller than this relative to the largest singular values are ignored.
5.full: bool
This an optional parameter that switches the determining nature of the return value. By default, the value is set to false due to which only the coefficients are returned. If the value is specified to true, then the decomposition singular value is also returned.
6.w:array_like
This optional parameter represents the weights to apply to the y-coordinate of the sample points.
7.Cov:bool or str
This optional parameter if given and not false returns not Just an array but also a covariance matrix.
Return
P: nadarray
It returns the polynomial coefficient with the highest power first.
residuals, rank, rcond
We get this only if the “full=True”. Residual is the sum of squared residuals of the least square fit.
V: ndarray
We get this only if the “full=false” and “cov=true”. Along with that, we get a covariance matrix of the polynomial coefficient estimate.
Examples Of Numpy Polyfit
Now let us look at a couple of examples that will help us in understanding the concept. At first, we will start with an elementary example, and moving ahead will look at some complex ones.
#input import numpy as ppool x=[1,2,3] y=[3,45,5] print(ppool.polyfit(x,y,2))
Output:
[ -41. 165. -121.]
In the above example, we can see NumPy.polyfit(). At first, we have imported NumPy. Moving ahead we have defined 2 arrays X and Y. X here represents all the points we want to represent along the X-axis and similarly for Y. Then we have used our defined syntax name. polyfit(x,y, deg) and a print statement to get the desired output. In this example, we have not used any optional parameter.
Now let us see a more complex example.
#input import numpy as ppool x=[1,2,3] y=[4,5,6] print(ppool.polyfit(x,y,2,full="true"))
(array([-1.3260643e-15, 1.0000000e+00, 3.0000000e+00]), array([], dtype=float64), 3, array([1.67660833, 0.43259345, 0.04298142]), 6.661338147750939e-16)
In the above example, again, we have followed similar steps as in the above example. But this time, we have used the optional variable full and defined it as true. The difference can be spotted in the output as we get a residual.
Now let us look at one more example
#input import numpy as ppool x=[1,2,3] y=[4,5,6] print(ppool.polyfit(x,y,2,full="false",cov="true"))
Output:
(array([-1.3260643e-15, 1.0000000e+00, 3.0000000e+00]), array([], dtype=float64), 3, array([1.67660833, 0.43259345, 0.04298142]), 6.661338147750939e-16)
Similar to the above example with the only difference of “cov.” For this example we have added cov =”true” and specified full=”false”. As a result of which in output, we get a covariance matrix.
Plot Linear Regression Line Using Matplotlob and Numpy Polyfit
Code:
import numpy as np import matplotlib.pyplot as plt x = [1,2,3,4] y = [5,9,13,16] coef = np.polyfit(x,y,1) poly1d_fn = np.poly1d(coef) plt.plot(x,y, 'yo', x, poly1d_fn(x)) plt.xlim(0, 5) plt.ylim(0, 20) plt.show()
Output:
Explanation:
You can use the poly1d function of numpy to generate the best fitting line equation from polyfit. This equation can be used in plt.plot() to draw a line along with your data.
Must Read
- NUMPY INSERT IN PYTHON WITH EXAMPLES
- Understanding Python Bubble Sort with examples
- Numpy Gradient | Descent Optimizer of Neural Networks
- Understanding the Numpy mgrid() function in Python
- NumPy log Function() | What is Numpy log in Python
Conclusion
In this article, we have covered NumPy.polyfit(). NumPy digitize next. | https://www.pythonpool.com/numpy-polyfit/ | CC-MAIN-2021-43 | refinedweb | 886 | 67.76 |
SubnetRoute holds a BGP routing table entry. More...
#include <subnet_route.hh>
SubnetRoute holds a BGP routing table entry.
SubnetRoute is the basic class used to hold a BGP routing table entry in BGP's internal representation. It's templated so the same code can be used to hold IPv4 or IPv6 routes - their representation is essentially the same internally, even though they're encoded differently on the wire by the BGP protocol. A route essentially consists of the subnet (address and prefix) referred to by the route, a BGP path attribute list, and some metadata for our own use. When a route update from BGP comes it, it is split into multiple subnet routes, one for each NLRI (IPv4) or MP_REACH (IPv6) attribute. SubnetRoute is also the principle way routing information is passed around internally in our BGP implementation.
SubnetRoute is reference-counted - delete should NOT normally be called directly on a SubnetRoute; instead unref should be called, which will decrement the reference count, and delete the instance if the reference count has reached zero.
SubnetRoute constructor.
SubnetRoute constructor.
protected SubnetRoute destructor.
The destructor is protected because you are not supposed to directly delete a SubnetRoute. Instead you should call unref() and the SubnetRoute will be deleted when it's reference count reaches zero.
when a route is chosen by the routing decision process as the winning route for this subnet, set_is_winner should be called to record this fact and to record the igp_metric at the time the route was chosen.
set_is_winner should NOT be called by anything other than the DecisionTable because caching means that it may not return the right answer anywhere else
Replaced policy tags of route.
delete this route
unref is called to delete a SubnetRoute, and should be called instead of calling delete on the route. SubnetRoutes are reference-counted, so unref decrements the reference count and deletes the storage only if the reference count reaches zero. | http://xorp.org/releases/current/docs/kdoc/html/classSubnetRoute.html | CC-MAIN-2018-05 | refinedweb | 322 | 58.62 |
This book will take you on an exciting tour to show and teach you about game development using the open source LibGDX framework. Actually, you have chosen just the right time to read about game development as the game industry is in a remarkable state of change. With the advent of increasingly powerful smartphones and tablets as well as the ever-growing application stores for desktop computers and mobile platforms serving millions of users a day, it has never been easier for Independent Game Developers (also known as Indies) to enter the market with virtually no risks and very low budgets.
In this chapter, you will learn about what LibGDX is and the advantages that it provides when developing your own games. You will also get a brief overview of the feature set that LibGDX provides.
Before you can start developing games with LibGDX, you have to install and set up your development environment accordingly. You will be using the freely available and open source software Eclipse as your Integrated Development Environment (IDE) to set up a basic project that uses LibGDX. It will feature a runnable example application for every currently supported target platform. These platforms are as follows:
Windows
Linux
Mac OS X
Android (2.2+)
iOS
HTML5 (using JavaScript and WebGL)
You are going to explore what a game needs by looking at it from a technical standpoint, and why it is so important to plan a game project before the development starts.
At the end of this chapter, you will be introduced to the game project that is going to be developed and enhanced throughout this book.
LibGDX is an open source, cross-platform development framework, which is designed mainly, but not exclusively, to create games using the Java programming language. Besides Java, LibGDX also makes heavy use of the C programming language for performance-critical tasks to incorporate other C-based libraries and to enable cross-platform capabilities. Moreover, the framework abstracts the complex nature of all its supported target platforms by combining them into one common Application Programming Interface (API). One of the highlights of LibGDX is the ability to run and debug your code on the desktop as a native application. This enables you to use very comfortable functions of the Java Virtual Machine (JVM), such as Code Hot Swapping, which in turn lets you immediately see the effect of your changed code at runtime. Therefore, it will significantly reduce your time to iterate through different ideas or even to find and fix nasty bugs more quickly.
Another critical point is to understand that LibGDX is a framework and not a game engine that usually comes with lots of tools, such as a full-blown level editor and a completely predefined workflow. This might sound like a disadvantage at first, but actually it turns out to be an advantage that enables you to freely define your own workflow for each project. For example, LibGDX allows you to go low-level so you could add your own OpenGL calls if that really became necessary at some point. However, most of the time it should be sufficient enough to stay high-level and use the already built-in functionalities of LibGDX to realize your ideas.
Since the release of LibGDX Version 0.1 back in March 2010, a lot of work has been contributed in order to improve this library. The latest stable release of LibGDX is Version 1.2.0 from June 2014, which we are going to use throughout this book.
Here is a list of features taken from the official website ().
The graphic features are as follows:
Render through OpenGL ES 2.0 on all platforms
Custom OpenGL ES 2.0 bindings for Android 2.0 and higher versions that restores all textures, shaders, and other OpenGL resources
High-level 2D APIs:
Custom CPU side bitmap manipulation library
Orthographic camera
High-performance sprite batching and caching
Texture atlases with whitespace stripping support, which are either generated offline or online
Bitmap fonts (does not support complex scripts such as Arabic or Chinese), which are either generated offline or loaded from TTF files (unsupported in JavaScript backend)
2D particle system
TMX tile map support
2D scene-graph API
2D UI library, based on the scene-graph API, fully skinable
High-level 3D APIs:
The following are the audio features:
Streaming music and sound effect playback for WAV, MP3, and OGG
Direct access to audio device for PCM sample playback and recording (unsupported in JavaScript backend)
The various input features are as follows:
Using abstractions for mouse and touchscreen, keyboard, accelerometer, and compass
The gesture detector that detects taps, panning, flinging, and pinch zooming
The following are the features for the file I/O and storage:
Filesystem abstraction for all platforms
Read-only filesystem emulation for JavaScript backend
Binary file support for JavaScript backend
Preferences for lightweight setting storage
The math and physics features for LibGDX are as follows:
Matrix, vector, and quaternion classes. Matrix and vector operations are accelerated via native C code where possible.
Bounding shapes and volumes.
Frustum class to pick and cull.
Catmull-Rom splines.
Common interpolators.
Concave polygon triangulator.
Intersection and overlap testing.
JNI wrapper for Box2D physics. It is so awesome that other engines use it as well.
JNI wrapper for bullet physics.
The different utilities in LibGDX are as follows:
Custom collections with primitive support
JSON writer and reader with POJO (de-)serialization support
XML writer and reader
The LibGDX project enjoys a steadily growing and active community. If you ever find yourself stuck with a problem and you just cannot figure out how to solve it, check out the official forum at. There is a great chance someone else has already asked your question and has even found a solution with the help of the community. Otherwise, do not hesitate to ask your question on the forums.
There is also an official IRC channel (
#libgdx) on Freenode () where you can find some of the users and developers to talk about LibGDX.
If you want to read about the latest news on development of LibGDX, visit the blog of Mario Zechner who is the founder of the LibGDX project, or follow him on Twitter using the following links:
LibGDX website ()
Mario Zechner's blog () and the Twitter link ()
Also, check out the following links for more in-depth information:
Wiki ()
API overview ()
Before you can start writing any application or game with LibGDX, you need to download and install the library and some additional software.
To target Windows, Linux, Mac OS X, Android, and HTML5, you will need to install the following software:
Java Development Kit 7+ (JDK) (v6 will not work!).
Eclipse (the Eclipse IDE for Java developers is usually sufficient).
Android SDK; you only need the SDK, not the ADT bundle, which includes Eclipse. Install all platforms via the SDK Manager.
Android Development Tools for Eclipse, also known as ADT Plugin. Use this updated site ().
Eclipse Integration Gradle, use this updated site ().
To additionally target iOS, you will also need:
Mac, as iOS Development does not work on Windows/Linux, thanks to Apple
The latest Xcode, which you can get from the Mac OS X App Store for free
The RoboVM plugin
Due to the fact that LibGDX is a framework based on Java, it is necessary to download Java Development Kit (JDK). To install it, follow these steps:
The software is freely available on Oracle's website:. Enter this address and you will see the following page:
Click on the DOWNLOAD button to start downloading the latest JDK.
Note
It is important to choose the JDK instead of the JRE package. The reason is that the JDK package contains the Java Runtime Environment (JRE) to run Java applications and everything else that is required to develop them.
You will have to accept the license agreement and choose the version that is appropriate for your platform. For example, if you are using a 64-bit version of Windows, choose the download labeled as Windows x64. Here, we are using the 32-bit version that is labeled window-i586:
To install the JDK, simply run the downloaded installer file (for example,
jdk-8u5-windows-i586.exe) and follow the instructions on the screen:
On the welcome screen of the installer, click on Next to continue:
Then, keep all the features selected to be installed, and click on Next again to continue, as shown in the following screenshot:
Once the installation is complete, click on the Close button to exit the installer.
The next step is to download and install Eclipse, a freely available and open source Integrated Development Environment (IDE) in order to develop applications in Java. Go to and choose Eclipse IDE for Java Developers, as shown in the following screenshot, to download for the platform you are using:
Once the download is finished, extract the archive to
C:\eclipse\.
Go to and choose the
libgdx-1.2.0.zip file to download LibGDX.
Note
At the time of writing this book, the latest stable version of LibGDX is 1.2.0. It is recommended to use the same version while working with this book.
The following screenshot shows a list of all the available files:
In the meantime, create a new folder inside the root folder of your C drive with the name
libgdx. Once the download is finished, move the archive to
C:\libgdx\.
The Android mobile OS is one of LibGDX's supported target platforms. Before you can create Android applications, you have to download and install the Android SDK.
Go to and click on the Download the stand-alone Android SDK Tools for Windows button, as shown in the following screenshot. In case you are using an OS other than Windows, you will have to scroll down a bit further, click on Download for other platforms and choose the appropriate platform.
Once the download is finished, run the installer (for example,
installer_r22.0.4-windows.exe) and follow the instructions on the screen.
You will see the following screen when you try to install the Android SDK. This is because the installer cannot find the JDK although you have already installed it.
You need to set the value of the environment variable
JAVA_HOMEto the installation path of the JDK. To find the correct path, go to
C:\Program Files\Java\. You will see a folder starting with
jdk. Take the full name of this folder (here, it is
jdk1.8.0_05) and append it to its path, as shown in the following screenshot:
The complete path will now look like
C:\Program Files\Java\jdk1.8.0_05. Now you have to set the environment variable. Click on the Windows Start button and right-click on Computer. Then click on Properties to open the control panel system window, as shown in the following screenshot:
Click on Advanced system settings on the left-hand side of the window, as shown here:
The System Properties window will appear. Click on the Environment Variables button:
The Environment Variables window will appear. Click on the New button (at the top) that corresponds to User variables for <USERNAME> (the username in this case is andreas), as shown here:
A window with the title New User Variable will appear. Now, fill in the two text fields. Enter
JAVA_HOMEin the Variable name field and the JDK's path you found earlier in the Variable value field, as shown in the following screenshot:
Great! Now your system is prepared for the Android SDK installer. Make sure to exit the Android SDK installer if it is still running to let the change take effect. You will be presented with the next screen after the installer has restarted.
Now, back in the Android SDK setup, click on Next to continue the installation, as shown here:
The following screenshot will ask you to choose the users for which the Android SDK should be installed. Usually, the suggested Install for anyone using this computer selection is perfectly fine, so just click on Next to continue.
Now, choose the installation location on your computer. You can safely keep the suggested location and click on Next to continue:
After this, you will be asked to choose a start menu folder. Again, you can safely keep the suggestion and click on Install to start the installation process:
After the installation is complete, click on Next to continue:
Once the installation is finished, you can choose to start the Android SDK Manager. Leave the Start SDK Manager (to download system images, etc.) checkbox enabled and click on Finish to start the manager:
The Android SDK Manager enables you to download system images for the specific API levels you want to develop applications for. For up-to-date and detailed information about Android API levels, check out the link.
Now, choose at least Android 2.2 (API 8) and/or any other higher API levels that you might need and click on the Install 7 packages button to automatically download and install all the relevant files, as shown in the following screenshot. The reason why we want to use at least API level 8 is that the earlier versions before Android 2.2 do not support OpenGL ES 2.0, which we will need in later chapters. Using a certain API level also allows you to control the range of devices that you will be able to see and install on your application via the Google Play Store.
Once the download and installation process is finished, close the Android SDK Manager window.
Great! You are almost done setting everything up. The remaining steps involve running Eclipse for the first time and installing important plugins, which are required to develop applications for Android, iOS, and HTML5/GWT with Eclipse.
Open Windows Explorer, and go to the location where you extracted Eclipse (here,
C:\eclipse\), and simply run the program by double-clicking on the executable called
eclipse.
Eclipse will ask you to select a so-called workspace. This is the folder where all your projects will be saved. We want to use the
C:\libgdx\ folder we created a bit earlier:
Select the Use this as the default and do not ask again checkbox if you don't want to see this dialog box every time you start Eclipse. To proceed, confirm the dialog box by clicking on the OK button.
The first time Eclipse is started with a new workspace, it will greet you with a welcome screen. Simply click on the small cross (x) of the Welcome tab to close it:
You should now see the standard view of Eclipse, which is also called the Java Perspective. On the left-hand side, you can see the Package Explorer section, as shown in the following screenshot. This is where you will see and manage your different projects. This is all you need to know about Eclipse for the moment.
If you have never worked with Eclipse before, it might seem quite overwhelming with all these windows, toolbars, huge context menus, and so on. However, be rest assured that all the steps will be discussed in detail as required to make it easy for you to follow.
To install new plugins, go to the menu bar, and click on Help, and then click on Install New Software. This will open the Install window, where you can type the special repository URLs to browse for new plugins. Google provides a list of such URLs at. You have to choose the correct URL that corresponds with your Eclipse installation.
At the time of writing this book, Eclipse 4.3.2 (Kepler) was the most current version available. According to Google's website, the suggested URL for our version is.
Type the URL in the text field that is labeled Work with and press return to let Eclipse request a list of available downloads. Select everything in the list that is shown in Developer Tools to add support for Android applications. Then, select everything in Google Plugin for Eclipse (required) to install the required Eclipse plugin. Lastly, select Google Web Toolkit SDK 2.5.1 in SDKs to add support for HTML5/GWT applications and click on Next to continue:
Now, click on Next to start the installation:
You will now be prompted to accept the terms of the license agreements by selecting the I accept the terms of the license agreements option. You have to do this before you can click on Finish to continue, as shown in the following screenshot:
The download process should only take a couple of minutes, depending on the speed of your network connection. When downloading is finished, Eclipse will show a security warning that you are about to install unsigned content and wants to know whether it should continue or abort. There is always a potential risk of installing malicious software. However, in this case, the download is provided by Google, a well-known company, which is trustworthy enough. Click on the OK button to accept the warning and continue the installation, as shown in the following screenshot:
After the installation is finished, a final restart of Eclipse is required. Click on the Yes button to confirm the restart:
Now, let's install the Gradle plugin for Eclipse so that we can import the project into Eclipse via Gradle. For this, let's perform the previous steps again. Go to the Install New Software option in the Help menu.
Enter the URL in the Work with field:
Select Gradle IDE under Extensions / Gradle Integration and click on Next. Continue as you did while installing Eclipse plugins to finish the process.
Additionally, in order to enable the iOS development, you need to install the RoboVM plugin in Eclipse. RoboVM for Eclipse integrates the RoboVM AOT (ahead-of-time) compiler with the Eclipse Java IDE. With this plugin, you will be able to develop native iOS apps in Java and launch them on the iOS simulator and iOS devices from within Eclipse.
Note
To execute an application using RoboVM as backend, you need a Mac with Mac OS X 10.9 or higher version with Xcode 5.0 or higher version installed. However, you can construct the project in Windows and later copy it to Mac for execution.
To download and install the latest RoboVM plugin, we will perform the same steps that we did to install Eclipse plugins earlier. Go to the Install New Software option in the Help menu.
Enter the URL and continue, as shown in the following screenshot:
The latest RoboVM release while writing the book was v0.0.13.
Congratulations! You have just finished the installation of everything that you will need to develop and build your own games with LibGDX.
The next step is to create a new application. Usually, you would have to create several projects in Eclipse: one project for the shared game code, another one for the desktop launcher, and more for the Android, iOS, and HTML5/GWT launchers. Furthermore, the projects would also have to be configured and linked together in a certain way. This is quite a time-consuming task and more or less an error-prone process for inexperienced users.
Luckily, LibGDX provides tools to generate preconfigured projects for a new application that can be directly imported into Eclipse. There are two tools to create a LibGDX project, the latest one is using Gradle, and the old project setup tool written by Aurelien Ribon. First, we will learn about the old setup tool and then about the Gradle setup tool.
The old project setup tool is an executable JAR file called
gdx-setup-ui.jar.
Step 1
You can download the old setup tool from, as shown here:
Step 2
To run the tool, double-click on the
gdx-setup-ui file. When the program starts, click on the big Create button:
Step 3
In the next window, you will see a box labeled CONFIGURATION on the left-hand side. Here, you can configure what the tool will generate.
Enter
demo in the Name field, which defines a common project name for your application. Each launcher project will add its own suffix to it, such as
-desktop,
-android, or
-html. A preview of the outcome is shown in the OVERVIEW box on the right-hand side of the window.
The Package field defines the name of your Java package. This needs to be a unique identifier written in lowercase, which is usually derived from a reversed domain name. You do not have to own a domain name nor does it have to really exist, but it helps in choosing nonconflicting namespaces for Java applications. This is especially important on Android, as identical package names for two separate applications would mean that the already installed application is going to be overwritten by the second one while trying to install it. For this demo application, use
com.packtpub.libgdx.demo as the package name for now.
The Game class field defines the name of the main class in the shared game code project. Enter
MyDemo as the game class name.
The Destination field defines the destination folder where all the projects will be generated. Click on the blue folder button (just next to the field) and set the destination folder to
C:\libgdx\.
In another box called LIBRARY SELECTION, the status of required libraries is shown. If there is any item listed in red, it needs to be fixed before any project can be generated. You will see LibGDX being listed in red in the Required section. Click on the blue folder icon next to it:
Step 4
Then, choose the downloaded archive file
libgdx-1.2.0.zip from
C:\libgdx\ and click on Open, as shown in the following screenshot:
Step 5
The text color of the LibGDX label should have changed from red to green by now. Click on the Open the generation screen button to continue:
Step 6
Next, click on the Launch! button to generate all the projects, as shown here:
Step 7
All done! You can now go to Eclipse and start importing the generated projects into your workspace. To do this, simply navigate to the Import option in the File menu.
Step 8
In the Import dialog box, open the General category, select Existing Projects into Workspace, and click on the Next button, as shown here:
Step 9
Click on the radio button Select root directory and enter
C:\libgdx in the text field. This is the directory where all your generated projects were created. You need to confirm your text input by pressing the return key once. Eclipse will start to scan the directory for your projects and list them. Leave all checkboxes selected and click on the Finish button, as shown in the following screenshot:
Step 10
Eclipse will automatically try to build (compile) all the four newly imported projects in your workspace and probably fail. There are two issues that need to be resolved manually after the import. The first one is reported directly to the Console window in Eclipse. It complains about being unable to resolve the target android-15, as shown in the following screenshot:
You have to open the project properties of the
demo-android project. First, select it in the Package Explorer box on the left-hand side. Then, go to the menu bar and navigate to Properties option in the Project menu:
Step 11
The title of the window will say Properties for demo-android. If this is not the case, close the window and make sure you have selected the correct project and try again. Next, select Android from the list on the left-hand side. You will see a list of targets that are available on your system. Select Android 2.2, which uses API level 8, and click on the OK button, as shown here:
Step 12
Eclipse will recognize the change and successfully build the Android project this time.
The second issue requires you to click on the Problems tab in Eclipse. Open the Errors list and right-click on the reported problem, which will say The GWT SDK JAR gwt-servlet.jar is missing in the WEB-INF/lib directory. Choose Quick Fix from the context menu, as shown in the following screenshot:
Step 13
In the Quick Fix dialog box, select Synchronize <WAR>/WEB-INF/lib with SDK libraries as the desired fix and click on the Finish button, as shown here:
The two issues will be solved by now, which means that all the projects are now automatically built without failure and can be compiled.
Note
Though the steps to create a project using
gdx-setup-ui might seem difficult, actually it's very easy. In our book, we will generate the project setup for our first game using this setup tool, and later in Chapter 14, Bullet Physics, we will use the Gradle-based tool to generate the project, thereby mastering the two technologies.
For the first game, we will use the projects generated using the old setup tool; however, read this section and understand how it works, so that we can use it later in Chapter 14, Bullet Physics.
You can download the
gdx-setup.jar file from and then click on Download Setup App, as shown in the following screenshot:
However, we have already downloaded the
libgdx-1.2.0.zip file, which contains
gdx-setup.jar; hence, we will extract
gdx-setup from the archive. To run the tool, double-click on
gdx-setup to get the following screenshot:
The Name, Package, Game Class, and Destination fields are the same that we learned for the old project setup tool.
The
Android SDK field defines the path to where you have installed your
android sdk. Click on the Browse button and set it to the
android sdk folder. Here, it's
C:\Program Files\Android\android-sdk.
We will now select Release 1.2.0 from the drop-down list in the Libgdx Version field. Next under the Sub Projects tab, you can select the hardware platforms that you want to support. Here, we select all four, namely, Desktop, Android, Ios, and Html.
Finally, you can select the extensions (for example,
box2d,
physics bullet, and so on) to be included in your app. Some might not work on all the platforms for which you'll get a warning. For the demo, we don't need any extensions, hence ignore this part.
Note
Once chosen and created, you will have to add new hardware platforms or extensions manually. For manually adding dependencies, visit.
Now, click on the Advanced button, enable Eclipse, and then click on Save, as shown in the following screenshot:
Now that we have set everything, click on Generate.
Note
The
gdx-setup option will prompt you to download and install the latest SDK platform and build tools. Just ignore this. While writing the book, the SDK platform was 19 and build tools were 19.0.3.
It will take a while to download and generate the projects. Make sure that you are connected to the Internet. Finally, it will display BUILD SUCCESSFUL like this:
This means you are now ready to import the project into your IDE, run, debug, and package it! All done! You can now go to Eclipse and start importing the generated projects into your workspace.
You can import projects to Eclipse as in the old project setup by following Step 7 to Step 9. However, in order to access the features of the Gradle plugin, you need to import it quite differently. Navigate to the Import option in the File menu. In the Import dialog box, select the
Gradle Project subfolder from the
Gradle folder, as shown in the following screenshot:
Now in the Import Gradle Project window, click on Browse and select the folder where you created the demo project. Here, it's
C:\libgdx. Then, click on the Build Model button:
It will take a while to build the project. After this, select the different projects and click on Finish, as shown in the following screenshot:
All done! After importing, change the API level of Android to 8 by following Step 10 and Step 11 from the old project setup.
Before entering into the game, let's make a quite distinction between the two project setup tools. Why choose one over the other?
There is no doubt that the Gradle-based setup tool is the best. One of the biggest advantages of using Gradle is the dependency management system. The dependency management system is quick, simple, efficient, and easy. If you are developing a simple project without any extensions such as Box2d, you might use the old setup tool; however, if you are developing a multi-platform project, which might be updated soon, then you can use the Gradle-based setup tool.
The projects generated using Gradle and the old setup tool have some minor naming differences that are illustrated in the following figure:
The Java classes shown in the preceding figure are starter classes; we will learn about them in the next chapter. Although the names for projects, packages, and classes generated by the two tools are slightly different, other aspects of the projects such as the assets folder, manifest files, and project wiring are the same.
Note
All the chapters in this book will be explained based on the projects generated from the old setup tool. However, understanding projects generated from Gradle is very easy because the names are easily comparable.
The old setup tool (
gdx-setup-ui) is now not encouraged by LibGDX and it might be phased out later; however, it is included in this book because it will be useful for smaller projects.
You can also see that the projects generated and organized under the
C:\libgdx path are different for both tools. The old setup tool (
gdx-setup-ui) creates all the five projects in the respective folders, as shown in the following screenshot:
However, the Gradle-based tool (
gdx-setup) creates a lot file, as shown here:
Observe that our projects are named
core,
android,
desktop,
html, and
ios. Additionally, take a note of the
build.gradle file. This file is important because this is the file you need to edit in order to add more dependencies (such as hardware platform) or new extensions (such as Box2D or Bullet).
Let's take a moment to discuss what a game basically consists of. From a very high-level point of view, a game can be split up into two parts: game assets and game logic.
Game assets include everything that is going to be used as a kind of working material in your game, such as images, sound effects, background music, and level data.
Game logic is responsible for keeping track of the current game state and to only allow a defined set of state transitions. These states will change a lot over time due to the events triggered either by the player or by the game logic itself. For example, when a player presses a button, picks up an item, or an enemy hits the player, the game logic will decide the appropriate action to be taken. All this is better known as gameplay. It constrains the ways of action in which a player can interact with the game world, and also how the game world would react to the player's actions.
To give you a better idea of this, take a look at the following diagram:
The very first step is to initialize the game, that is, loading assets into memory, creating the initial state of the game world, and registering with a couple of subsystems, such as input handlers for keyboard, mouse and touch input, audio for playback and recording, sensors, and network communication.
When everything is up and running, the game logic is ready to take over and will loop for the rest of the time until the game ends and will then be terminated. This kind of looping is also referred to as the game loop. Inside the game loop, the game logic accumulates all (new) data it is interested in and updates the game-world model accordingly.
It is very important to consider the speed at which updates will occur in the game world. Currently, the game will just run at the maximum speed of the available hardware. In most cases, this is not a desirable effect because it makes your game dependent on the processing power and the complexity of the scene to be rendered, which will vary from computer to computer. This implies that your game world will also progress at different speeds on different computers with an almost always negative impact on the gameplay.
The key to tackle this issue is to use delta times in order to calculate the fractional progress of the game world. The delta time is the real time between the last rendered frame and current frame. Now, every update to the game world will occur in relation to real time that is passed since the last frame was rendered. You will see how this actually works with LibGDX in the later examples.
What you have just read was an overview of the basic concept to create games. Yes, it is that simple! Frankly speaking, there is a lot more to learn before your application becomes a real game. There are lots of topics and concepts waiting to be discovered in this book. For instance, you will need to understand how to use and manage different images in an efficient manner. Efficiency becomes even more important if you plan to target mobile devices such as Android or iOS smartphones, where the available resources are constantly scarce.
Great! Now you have your development environment set up and a basic understanding of what a game is and what it might need. It appears to be a good idea to dedicate some additional time to think about your first game project and create a plan for it. In general, planning your game projects is what you should always do in the first place before any actual work is done. For novice game developers, it might be very tempting to skip this planning phase, which admittedly is a lot more fun in the beginning, but this approach is very likely to fall short in the long run. You will need some sort of outline of what you want to achieve. It does not have to be a very long and detailed description.
A simple and brief feature list of your design goals will do just fine for this purpose. The reason behind this is that you will make yourself aware of each single feature that is a part of your game. In addition, this list will also serve you as a great tool to measure and compare your progress in the game during the development phase. Bear in mind that game development is a very dynamic and iterative process. Although, you should try to adhere to your list of design goals for most of the time, there should always be room to adapt to shifting requirements. Just keep in mind that adhering to the list will make sure that you are going to push development in the right direction. Conversely, it will let you focus on the important parts first, while also protecting you from running out of time and taking too many detours, which prevents you from reaching the finish line due to unclear goals.
To make this guide both easy and fun to read, it makes perfect sense to show you how to plan and develop a whole game project throughout this book. As we now know, planning should be the first step to take on the journey of any new game project.
So, let's begin with the outline:
The name or working title for the game will be Canyon Bunny
The genre will be 2D side-scrolling jump and run
The list of actors are as follows:
The player character (can jump and move forward and will be controlled by the player)
Rocks will be serving as platforms for the player character and items
Canyons in the background (for level decoration)
Clouds in the sky (for level decoration)
Water at the bottom of the level (which will be deadly for the player character)
Collectible items (such as gold coins and feather power-up) for the player
Next, it is always helpful to write down some supporting text to further describe the overall behavior of the game, and how the features should be implemented.
The game world is presented in a 2D-side view to the player. The view will scroll horizontally to the right-hand side when the player character moves forward. The background shows distant canyons and clouds in the sky. The bottom of the level is filled with water and will instantly kill the player character if both get in touch with each other.
The player character will move on and jump over to random rocks, sticking out of the water. The width and height will be different to make the game more challenging. The player is only in control of a jump button, which will keep the automatically forward-moving player character from falling down into the deadly water.
The level will be randomly populated with collectible items consisting of gold coins and feather power-ups. Collecting the gold coins will increase the player's high score. The feather power-up grants the player character the ability to fly for a limited time and can be used by repeatedly pressing the jump button. The player's goal is to beat the last high score.
As a picture is worth a thousand words, creating a sketch based on our outline can help us even more to get a better idea of the resulting game. Moreover, changing a sketch is usually a lot easier than having to change (complex) game code. So, you really want to keep it very simple; just grab your pen and paper and start to draw. If you feel lucky or have some time to spend, you can do something more elaborate, of course.
Here is a mock-up for Canyon Bunny:
The previous mock-up has been created entirely by using vector graphics. Using vector graphics in favor of raster graphics for your sketches can be an advantage as they are infinitely scalable to any size without losing the image quality. However, the final graphics used in games are almost, always, rasterized graphics, simply because vector graphics are costly to render in real time. So, the common approach is to create vector graphics and later on export them choosing an appropriate rasterized graphics file format, such as Portable Network Graphics (PNG) for lossless compression with alpha channel support, or Joint Photographic Experts Group (JPEG) for lossy but high compression without alpha channel support.
For more details, check out the following Wikipedia articles:
For information on raster graphics, visit
For information on vector graphics, visit
For information on PNG file format, visit
For information on JPEG file format, visit
There is a free and open source tool called Inkscape similar to Adobe Illustrator. It allows you to easily create your own drawings as vector graphics and is available for Windows, Linux, and Mac OS X. Check out the project's website.
We learned a lot about LibGDX in this chapter and all the other bits and bobs to prepare your system for multi-platform game development, specifically on the following points:
We discussed every step in great detail to successfully download, install, and configure all the required software components: JDK, Eclipse, LibGDX, Android SDK, and additional Eclipse plugins for Android, HTML5/GWT, and RoboVM.
We learned how to use the project setup tool that comes with LibGDX to easily generate all the required Eclipse projects for a new application and how to import them. We also learned what a game needs to come alive.
We found out why planning game projects is so important.
We also saw how to plan a game project by writing an outline.
In Chapter 2, Cross-platform Development â Build Once, Deploy Anywhere, we will learn more about how to deploy and run a LibGDX application on all supported target platforms. Building on this knowledge, we will finally jump to the first code examples where the magic happens and take a closer look at it to find out how it works. | https://www.packtpub.com/product/learning-libgdx-game-development-second-edition/9781783554775 | CC-MAIN-2020-50 | refinedweb | 6,755 | 67.99 |
Important changes to forums and questions
All forums and questions are now archived. To start a new conversation or read the latest updates go to forums.mbed.com.
4 years, 4 months ago.
BLE FOTA triggered from app without enabled softdevice?
I am interested in using FOTA but would like to trigger bootloader from app that does not have a running Softdevice. I tried using the following to set the GPRERET register then trigger system reset but does not work. Any ideas?
NRF_POWER->GPREGRET = BOOTLOADER_DFU_START; BOOTLOADER_DFU_START= 0xB1; NVIC_SystemReset();
A simple example would be an app that flashes an LED and a button press triggers a jump to DFU bootloader. The button press would not be at start up but rather anytime. This app but not be running anything from BLE_API and would not use ble.init().
This assumes the bootloader code would do the initial BLE stack init and begin advertising.
#include "mbed.h" DigitalIn enable_DFU(p5); DigitalOut led(LED1); int main() { while(1) { if(enable_DFU) { // jump to DFU / FOTA } wait(0.25); led = !led; } }
Please explain what you mean by: "would like to trigger bootloader from app that does not use BLE/Softdevice". Without the softdevice none of this would work. Do you mean without BLE_API?posted by Rohit Grover 05 Nov 2015
I updated my question.posted by joel anderson 05 Nov 2015 | https://os.mbed.com/questions/61423/BLE-FOTA-triggered-from-app-without-enab/ | CC-MAIN-2020-16 | refinedweb | 225 | 66.54 |
Desktop K8S in 2021
Is there a better alternative to Minikube? See some options for Local Kubernetes Clusters if you are developing on a Mac.
Join the DZone community and get the full member experience.Join For Free
For this article, we’ll dig into some of the options for Local Kubernetes Clusters if you are developing on a Mac. When doing microservices development, eventually you will want to start to test integrated services together. And there are several options available to run these tests:
- Dedicated Clusters – Larger teams typically have dev environments and you can either run lots of little clusters or a big cluster with lots of namespaces in them. Running clusters 24/7 costs real money that can add up quickly. Also if you opt for big clusters with namespaces per developer, this is still not a good reflection of staging or production.
- Docker Compose – This is an old standby and one we still use for certain workloads. You can quickly spin up a chain of images and network them together. One big drawback I find to using docker compose is that the manifests are not used in my staging and production clusters. This ends up being work only for the developer desktop.
- Local Kubernetes Cluster – With a local cluster you can use the exact same manifests that are used in staging and production. Of course you need local hardware that can support the load, but the infrastructure requirements for this have come way down.
Tests were conducted on a 2019 MacBook Pro (Big Sur).
$ kubectx docker-desktop microk8s minikube rancher-desktop
Minikube
I’m not embarrassed to say that I cut my teeth on minikube. This is the recommended path for onboarding into Kubernetes and has a ton of benefits:
- Much of the standard Kubernetes documentation applies to minikube
- With over 20K stars on GitHub it is one of the most popular repos out there and is incredibly active
- It runs a VM that with a single node cluster, and you can swap out the VM if you want to use a different engine
Source: GitHub minikube
Microk8s
Several years ago Canonical released microk8s, their own distribution of Kubernetes. It is available directly into Ubuntu through snap. Because it is designed for running in Linux, this may be a good choice if you prefer to interact with everything over the command-line. There are tons of built-in commands and features, and it also has the ability to automatically pull in lots of other open source projects.
- It is built right into Ubuntu which is one of the most popular Linux distros, but it can also be deployed on Mac through brew
- On a Mac it will spin up a VM using Multipass that runs ubuntu with microk8s inside
- Microk8s includes a bunch of standard add-ons for instance if you want to test out a service mesh or particular kind of ingress
- The instructions all assume you type microk8s before your kubectl commands, so you’ll want to add the context to your config instead
Rancher Desktop
As a new entrant to the local Kubernetes cluster, Rancher Desktop takes a completely different approach. Instead of Kubernetes, it spins up a thin k3s cluster under the hood. Rancher has packaged this tool as an electron app. It runs a thin VM and images are maintained using KIM (also an experimental project).
- Easily switch between different versions of Kubernetes with a simple drop-down
- Built-in UI for doing things like port-forwarding with a single click
- It uses a surprisingly small amount of resources for an app built on top of electron
- At the time of this article it is still in alpha version, so expect more things to change over time
Source: Ken’s Incredible MacBook Pro
Docker Desktop for Mac
If you are doing development on a Mac and dealing with Dockerfiles, chances are you have Docker Desktop deployed. This is a closed source project, although you can open issues on GitHub. This is a very active project, docker pushes out updates regularly. One of the built-in features of Docker Desktop is that you can turn on the included Kubernetes cluster. This works in a unique way:
- It does not use a VM but deploys docker-in-docker across a set of nodes running as docker images themselves which is neat
- You can run your regular docker ps command to see things that are running inside the cluster
- Docker recently changed their policy that you must update to new versions unless on a paid plan, so this may force an unexpected upgrade
- It is not as easy to switch between Kubernetes distributions, you must “reset” your cluster in Docker Desktop to allow an upgrade
Source: Docker Desktop Documentation
Summary
Fortunately, there are still a ton of options for Kubernetes local development in 2021. Hopefully this inspires you to run some test workloads on a new platform as well.
Published at DZone with permission of Ken Ahrens. See the original article here.
Opinions expressed by DZone contributors are their own. | https://dzone.com/articles/desktop-k8s-in-2021?fromrel=true | CC-MAIN-2021-43 | refinedweb | 846 | 54.46 |
on proposed itin from London: EDINBURGH & EILEAN DONAN-HELP PLEASE! totally blew up about the HARRYPTOUR UK tickets
United Kingdom
Travel Forums
Dinner–Late night drink
help on proposed itin from London: EDINBURGH & EILEAN DONAN-HELP PLEASE! totally blew up about the HARRYPTOUR UK tickets
help on proposed itin from London: EDINBURGH & EILEAN DONAN
Help on rail rd tickets
Help on restaurants 4dinner, lunch & breakie (while we @it)
help on route from inverness to kyle of lochalsh
Help on route please.
Help on Scotland Trip
Help on scotland visit
Help on selecting a desitnation
Help on sim cards
Help on the best places to visit with a 13 Year old
Help on the Bus!
Help on the West End
Help on tight connection from Waterloo (Eurostar) to Gatwick
Help on timing
help on train from Bath to London
help on transport from London Heathrow T3 to Slough
Help on Transportation
Help on Transportation from Airport and 1-Day Trips
Help on transportation plans in London
Help on transportation to and from Inverness airport
Help on Travel
Help on travel . Twickenham , Wandsworth, Tottenham.
Help on travel plan for cotswould
help on Travel to Stansted
Help on travel to ullapool
Help on Travelcard please!
Help on Travelling the Underground from Hethrow to the St. T
Help on tube route from Heathrow airport with 24' luggage
help on where to start!!
Help on where to stay
Help on where to stay...
Help One More Time Please???
Help one night in London
Help organize days in London
help organizing day trips from London in October
Help Organizing Itinerary
help organizing London geographically for family trip
Help organizing quick visit to London
Help parents coming to London to visit!
Help parking In Camden
Help passport problems
help phone advice needed
Help picking a fab hotel please
Help picking a hotel
Help picking a musical
Help picking a reasonable hotel and good location
Help picking a self-catering apartment please
help picking a travel week
Help Picking Flat - What Neighborhood?
Help picking flights betweem AA, British Airways, Virgin
Help places to stay between Salisbury and Winchester
Help plan 2 weeks in Europe
Help plan 3 day itenary
help plan a route from Portree to Edinburg
Help Plan a trip
Help plan a trip for family with two older teen boys
help plan a visit to Yorkshire for 60th birthday
Help plan end of Jan trip for 40th bday pls
Help plan itinery
help plan my around wales self drive trip
Help Plan My Itinerary
Help plan my journey please
Help Plan my Trip Edinburgh
Help plan one perfect day in London?
Help plan our itinerary please
Help plan our short Highlands road trip
Help Plan Our Trip
Help Planning
Help planning
Help planning
Help planning 10-12 day trip through the UK
Help Planning 18 Day Trip to United Kingdom
Help planning 2 days
Help planning 2 days in June
help planning 2 days in the Highlands
help planning 2 nights in London-
Help Planning 2 weeks including National Parks
Help planning 3 day trip to Wales
Help planning 3.5 day itinerary please!
HELP planning 7 wonderful nights in Scotland!
help planning 8 day trip to scotland
Help planning a "Girl Friend Getaway" - 8 nights in Scotland
Help planning a 10th anniversary trip
Help planning a 2/3 days Cotswolds solo trip
Help planning a 5 Day self drive starting in London
Help Planning a bucket list trip
Help planning a day walk
Help Planning a Dream trip to Isle of Skye
Help planning a family holiday in Cornwall please?
Help planning a few days of beautiful walking in Scotland
Help planning a Hadrian's Wall Hike from USA?
Help planning a holiday in North Wales needed!!!
Help planning a itinerary
Help planning a Scotland driving tour!
Help planning a Scotland trip
Help Planning a Self-Ride B&B Tour of Scotland
Help Planning a Sunday in Greenwich
Help planning a trip to Europe
Help planning a trip to Pembrokeshire
Help planning a trip- London, Paris, Amsterdam
Help planning a weekend of walking without a car
Help planning an 11-day Scotland Itenerary
Help planning an 80th Birthday trip
Help planning an itinary
Help planning an itinerary!
Help planning attractions for a 5.5 days stay in London
Help Planning Birthday Weekend!!
Help planning civilised London hen party (dinner, show, bar.
Help planning Cornwall trip
Help planning day trip from Euston Station
Help planning Day trip to Portsmouth
Help planning DEC-JAN trip to England
Help Planning Drive from Edinburgh to Isle of Skye,then back
Help Planning Family History Trip: London, SE, SW, Midlands
Help Planning First London Trip (Last 2 days)
Help Planning First Trip to Scotland
Help planning for a trip to London in less than 30 days!!
Help planning for husband's 45th bday: tea, small plates, +?
Help planning for my visit to oxford
help planning girlie weekend for May bank holiday
Help planning Hadrian's Wall Walk
Help Planning Highlands Road Trip
Help planning Ireland-Wales-London trip?
Help planning itinerary & ticket information
Help planning itinerary 2009
Help planning itinerary from London to Inverness!!
Help planning itinerary please!
Help planning June Itinerary
Help planning London->Paris train vacation?
Help Planning My Itinerary
Help planning my trip from Carlisle to Cairnryan to Belfast
Help planning one week in North East
Help planning our 3-day visit
Help planning our few days in Edinburgh
Help planning our itenerary
Help planning our perfect Cornwall visit please
Help planning Oxford trip
Help planning romantic 25th anniversary!
Help planning Scotland, Ireland, Wales
Help planning short break for mum's 80th surprise trip!
Help planning six days in Belfast
Help planning some 30th birthday surprises for Belfast wknd!
Help Planning Trip
Help planning trip 21-24 December
Help Planning trip to Cornwall
Help planning trip w.r.t National Trust sites near London
help planning UK trip
Help Planning UK Trip
Help planning visit to Yorkshire Moors
Help planning week in London and a Madness concert!
Help planning week long Northern Ireland Self Drive
Help Planning Week Long Self Drive in Scotland + Orkney
Help planning weekend
help planning weekend trip to bath and stonehenge ! Costwolds !
Help Please !! Where to eat in London
Help Please !!!! Off Peak Day return (train)
Help please , itinery
help please - 3 day trip
HELP PLEASE - Advice...train from London to Paris
help please - berry baron and axevale static sites
Help please - best London to Heathrow during rush hour
Help Please - Camping in Tintagel Area
Help Please - City Road Area
Help Please - Edinburgh photography and surrounds
Help please - Farmhouse or Le Havelet
Help Please - Getting To Heathrow
Help please - I don't know where to start!!
Help please - london accommodation
Help please - looking at the Holiday Parks around Weymouth
Help Please - Need Urgent Travel Advice
Help please - recommendations of London apartment Dec 2010
Help Please - Safe Area Suggestions
HELP please - stranded at Heathrow...
Help please - tube strike?
Help please - visit before Xmas where to base myself?
Help please - where to stay
Help please - which Premier Inn
Help Please -- Left package at York Rail Station
Help please --asap tube and tower of london question
Help please 1st time family to london
help please :)
Help please ?
Help please ?
help please airport hotel with shuttle
help please bus routes
Help please concerns regarding Hilton London Metropole
Help please dummy 241 ticket tomorrow!
Help please for 3-day stay.....
Help please for the Tattoo
Help please for travelling through Europe! :)
help please for virgin walking
HELP Please from the rail experts!
Help please getting info for travel from Bristol to Cardiff
help please help us find hotel---b/b nov thanks
Help please Hotel wanted close to suncastle December
help please how to get internet
Help please info about 2 4 1 from Richmond Station.
Help Please Itinery
Help please London Sightseeing
Help please Mancuians!
Help please nice small town in central Scotland
Help please on planes and trains (no automobiles...yet!)
Help please one day in London with teens
Help please oxford to London and back one day
Help please quickly re NW Highlands
help please re blackpool pleasure beach and price of bus
Help please recommend Inn
Help Please Scotland 16 Nights.
Help please staying in motel one princes street Xmas markets
help please the rain is coming!!
help please to tie up loose ends :)
Help please train journeys from Edinburgh
help please where to go
Help please with 5 day family trip June 2012
Help please with a brief stay in Southwest England (no car)
Help please with accommodation near Palace Rd, Tulse Hill
Help please with accommodation short list
Help Please with Advance Train Ticket - Chester to Glasgow
Help please with bus numbers
Help Please With Cotswold Itinerary
Help Please With Cotswold Itinerary
Help please with Edinburgh/England itinirary
help please with family get-together
Help please with final part of our plan.
Help please with Hotel Accommodation
Help please with legitimate apartment rentals!
Help please with LG Arena & Cadbury World?
Help please with London and The Cotswolds
HELP please with paying a Virgintrainseastcoast ticket
help please with pubs etc
Help please with timings - Heathrow to St Pancras (Eurostar)
help please with trains
help please with tube newbie to London
Help please!
Help Please!
Help please!
Help please!
Help please!
help please!
Help please!
Help please!
Help Please!
Help Please!
Help Please! Anglesey - best beach view/ budget stay
Help please! Apartment Rental Overload
Help Please! Arriving at Heathrow-Transport
HELP PLEASE! First Time Visitor To London Question!
Help please! 1st time going to Europe!
Help please! Eurostar tickets to Paris-URGENT help required
Help please! Itenerary for 6 days in London.
Help please! London stay locations
Help Please! Name of Hotel located next to yorkTrain Station
Help please! Need your expert advice/suggestions for London!
Help please! Sending parents to Edinburgh
HELP PLEASE! totally blew up about the HARRYPTOUR UK | https://www.tripadvisor.com/SiteIndex-g186216-o178-q2-sShowTopic-United_Kingdom.html | CC-MAIN-2019-47 | refinedweb | 1,647 | 64.75 |
Currently.
THIS IS NOT COMPLETE YET
See the following post for further discussion of the difference between the vision for a new PyLab expressed on this page, and the existing pylab package which is part of matplotlib:
The PyLab Vision
To make PyLab an easy to use, well packaged, well integrated, and well documented, numeric computation environment so compelling that instead of having people go to Python and discovering that it is suitable for numeric computation, they will find PyLab first and then fall in love with Python.
The philosophy behind this vision is to consider Rails and Ruby; while Ruby was somewhat popular beforehand, it was Rails which propelled it to the forefront.
At the moment, the current combination of Python, NumPy, SciPy, Matplotlib, and IPython provide a compelling environment for numerical analysis and computation. Unfortunately, for those who are not already familiar with Python and the intricacies of how to build your own Python environment, or for those not familiar with the details of how there are conflicting names exported by different modules, or how the best list of NumPy examples is found on the wiki in a non-obvious place (and that the docstrings are not the best documentation), or that the speed of linear algebra operators is dependent on a carefully compiled combination of LAPACK, ATLAS, and Goto BLAS, or a host of other reasons (some outlined below), the picture is not nearly so rosy.
Short-term Goals
Documentation - Dramatically enhance the standard documentation by consistently adopting the new DocstringStandard for all functions in the NumPy API.
API Consistency - Create an official API for the PyLab system such that there is an official way to import the PyLab packages, and such that there are not multiple functions with very similar names in different packages.
Installation - Make the installation process trivial, especially for, e.g. people without root access or spare time.
Build Process - Make the build process simple for the combination of the five core components (Python, NumPy, SciPy, Matplotlib, and IPython).
A simple user story
Joe is frustrated with Matlab, because he finds it is slow when running his neural network experiments. He hears about PyLab from a friend, who recommends it as an alternative.
He finds PyLab as the first search result on Google
He finds a page with minimal clutter, showing a couple pictures of PyLab, and a direct download link to a binary for his operating system. He notes that pylab.org must have determined he is running Linux automatically. The page also has a small number of big, clear links to promotional materials (screencasts, testimonials), documentation, and community information (how to get involved).
- After downloading, the program installs with no hassles, and Joe can launch Pylab by typing 'pylab' and pressing enter in a terminal. Joe is happy that there was no hassle over dependencies on his older university computer, and that installing directly into his home directory (he does not have root access on the university computers) is not a problem.
PyLab notices that it is the first time it is run, and suggests he read the tutorial, and provides a link.
Joe clicks the tutorial link, which his terminal automatically pops up in a browser. The tutorial covers the basics of PyLab, explaining some of the philosophy. The tutorial is clearly written, and covers the basics of array computation and 2D graphing.
When Joe is implementing code, he finds the interactive help invaluable, provided by typing any object or function with a '?' after it in the interactive prompt. The documentation has copious examples and helpful pointers to other functions which may be useful (See also:).
Joe implements and runs his neural network simulations, and manages to speed them up by using one of the several methods of optimizing computation in the tutorial. He is so pleased with the results he suggests to his instructor that the entire class should switch to PyLab, as it is free and as far as Joe can tell, superior in almost every way to MATLAB.
There are some details omitted here (such as in step 3, does Joe untar the downloaded file or is it an executable?), but those are not the point. The point is that PyLab is a compelling, integrated, usable and superior alternative to MATLAB.
Why the PyLab name? Isn't that already taken by Matplotlib?
PyLab should be the name of the entire suite, and I feel strongly that the correct way to import the entire core PyLab API should be via
from pylab import *
This should include the core parts of numpy, scipy, and matplotlib. This should also be the default namespace set up when the program is launched interactively via 'pylab'. Whether the other components (such as numpy.linalg.*) should be included in this import is up for debate.
1. Revamping the Documentation
For now this section only talks about docstrings, and ignores the other forms of documentation (tutorial, guide, etc). If you want to fill out this section please do!
Docstring standard
Travis Oliphant posted a draft docstring standard on January 10th 2007 which is the basis for the following proposed standard, which is now the DocstringStandard page. Please look at it.
Available modules in docstrings
Examples in docstrings are extremely valuable. However, it is currently never the case that the docstrings in either NumPy or SciPy use any of the functionality offered by matplotlib. This in unfortunate, especially in the case of SciPy, because often the clearest way of demonstrating a function is to plot something.
While it is true that there is an argument which says that SciPy should not become dependent on matplotlib, it appears that this dependence already exists for all intents and purposes. It is likely that only in the most extreme cases one would want to use SciPy without matplotlib. Furthermore, the dependency would only be in the case where a user is executing docstrings in the interactive interpreter; in this case, it is highly likely that the user is doing something which requires some sort of plotting package regardless.
2. Fixing API consistency
The current PyLab ensemble has issues with API consistency, mainly stemming from Matplotlib's compatability layer. For example, consider the load function, which exists in both NumPy and Matplotlib:
>>> from pylab import * >>> load.__doc__ '\n Load ASCII data from fname into an array and return the array.\n\n ....' >>> from numpy import * >>> load.__doc__ 'Wrapper around cPickle.load which accepts either a file-like object or\n a filename.\n '
This function isn't matched! They are clearly different, yet each accepts a filename, and each will break in mysterious ways when one is expecting the functionality of the other. This is especially hard to track down when one is editing a script and running it where the script's import order causes numpy.load to be present, but in the interactive terminal the user has open pylab.load is the exposed function. This is bad.
Another example is the confusion around the min and max functions overwriting the builtins, then breaking in weird and unexpected ways. It appears this is now sorted out, with numpy.amax and numpy.amin being the array versions, with numpy.min and numpy.max new names for numpy.amin/amax. I feel as though from numpy import * should import min and max, but import a min and a max that throw an exception!
Here's a list of conflicts between SciPy and Matplotlib:
1 In [12]: import pylab 2 In [13]: import scipy 3 In [14]: p=set(dir(pylab)) 4 In [15]: s=set(dir(scipy)) 5 In [16]: k=p.intersection(s) 6 In [17]: conflicts = [f for f in k if getattr(scipy, f) is not getattr(pylab, f)] 7 In [18]: import matplotlib 8 In [19]: matplotlib.__version__ 9 Out[19]: '0.87.7' <--- this was a pre 0.90 svn IIRC 10 In [20]: conflicts[0] 11 Out[20]: 'cumsum' 12 In [21]: pylab.cumsum? 13 Type: function 14 Base Class: <type 'function'> 15 String Form: <function cumsum at 0xb6731924> 16 Namespace: Interactive 17 File: /usr/lib/python2.4/site-packages/numpy/oldnumeric/functions.py 18 Definition: pylab.cumsum(x, axis=0) 19 Docstring: 20 <no docstring> 21 22 In [22]: scipy.cumsum? 23 Type: function 24 Base Class: <type 'function'> 25 String Form: <function cumsum at 0xb774d5a4> 26 Namespace: Interactive 27 File: /usr/lib/python2.4/site-packages/numpy/core/fromnumeric.py 28 Definition: scipy.cumsum(x, axis=None, dtype=None, out=None) 29 Docstring: 30 Sum the array over the given axis. 31 32 In [23]: conflicts 33 Out[23]: ['cumsum', 'ptp', 'fix', 'ravel', '__file__', 'ones', 'rank', 'tri', 34 'insert', 'arange', 'indices', 'loads', 'where', 'mean', 'argmax', 'nonzero', 35 'asarray', 'sum', 'polyfit', 'prod', 'log2', 'power', 'cumproduct', 'corrcoef', 36 'meshgrid', '__name__', 'cov', 'cumprod', 'vander', 'arccos', 'load', 'array', 37 'iterable', 'eye', 'log', 'sometrue', 'alltrue', 'zeros', 'log10', '__doc__', 38 'empty', 'polyval', 'arcsin', 'arctanh', 'linspace', 'typecodes', 'copy', 39 'std', 'fromfunction', 'argmin', 'trapz', 'binary_repr', 'sqrt', 'take', 40 'product', 'repeat', 'trace', 'compress', 'array2string', 'amax', 'identity', 41 'amin', 'fromstring', 'average', 'base_repr', 'reshape']
Most of these are via oldnumeric, but not all. Either way, all oldnumeric functions exposed via pylab shouldn't be.
The single import statement
What most users want is for a single import statement to get a consistent set of packages which fulfil most of their needs. This should consist of:
from pylab import *
That gets them NumPy, SciPy, and Matplotlib. A rough equivalent would be:
1 from pylab import * 2 from numpy import * 3 from scipy import *
But there are so many names!
Not really. from scipy import * brings in about 20 subpackages (i.e. signal such that you still need to do signal.ifft, but not scipy.signal.ifft) and only 15 new symbols.
How to fix the API
Fixing the API will involve a discussion between the core maintainers of each of the core modules (excepting IPython): NumPy, SciPy, and Matplotlib.
3. Fixing installation process
The installation process has certainly gotten easier over the years; however, the packages in PyLab core should be bundled in a cohesive whole so that the user is not even aware that there are several packages beneath the PyLab label. Certainly, for the busy undergrad who needs to get his signal processing homework done but can't afford MATLAB and doesn't have root access on his university computers it makes sense to have a monolithic binary which bundles everything (ala SAGE).
4. Fixing the Build process
Building a basic PyLab setup is straightforward on Debian and Ubuntu thanks to package management, provided one is capable of fishing around for the required build packages. However, a straight forward
python setup.py build
will not produce the most optimized executable; in order to get a highly optimized PyLab system, an elaborate dance is required to compile the BLAS, then Goto BLAS, then LAPACK with that BLAS, then replace a subset of LAPACK with optimized versions from ATLAS. The whole process is entirely unintuitive and, as far as the author can tell, not clearly documented anywhere, even for Linux.
Becoming a better foundation for SAGE
There is a package called SAGE which aims for almost exactly the same goals as PyLab. However, it is even more extreme than the PyLab vision outlined here, because SAGE includes many third party programs for cutting-edge support of symbolic computation. It also makes some incompatible changes to the Python syntax.
SAGE is built from a core of Python, IPython, and NumPy. In a posting to the SAGE developer list, the lead SAGE developer, William Stein, described how he wishes NumPy and SciPy would follow more consistent documentation standards. Shortly thereafter Travis Oliphant committed the documentation standard which should be used in NumPy and SciPy. By slowly working the docstring documentation into a consistent state, PyLab can form a more consistent and usable foundation for SAGE. | http://wiki.scipy.org/PyLab | CC-MAIN-2014-10 | refinedweb | 1,978 | 51.89 |
Working.
As with all good things: you learn to appreciate it even more if you do not have it any more. And this happens to me when I moved to ColdFire, PowerPC and Kinetis applications using CodeWarrior build tools. I would expect that this kind of simple thing would be there, but…. nada. I need to open the map file.
GNU gcc for Kinetis: arm-none-eabi-size
With the advent of gcc for Kinetis in CodeWarrior for MCU10.3 (see the Freedom board posts), there is finally some relief. GNU gcc is here the default compiler for the Kinetis L family. The KL25Z which is on the FRDM-KL25Z Freedom board has decent RAM and Flash, but the L series really is targeting the small and tiny microcontrollers. And here code and data size information right at link time is important, as it is e.g. for the S08. And with the move of Freescale to gcc, the arm-none-eabi-size is part of the tools: it is part of the GNU tools for ARM Cortex M0+. I can find that tool inside
<installationPath>\Cross_Tools\arm-none-eabi-gcc-4_6_2\bin\arm-none-eabi-size.exe
Command Line Interface
Executing that tool from the command prompt/DOS Shell with the option -help provides pretty much everything needed:
C:\Freescale\CW MCU v10.3\Cross_Tools\arm-none-eabi-gcc-4_6_2\bin>arm-none-eabi-size.exe -help Usage: arm-none-eabi-size.exe arm-none-eabi-size.exe: supported targets: elf32-littlearm elf32-bigarm elf32-little elf32-big srec symbolsrec verilog tekhex binary ihex
Executing the utility with
arm-none-eabi-size.exe c:\wsp_Freedom\Freedom_Accel\FLASH\Freedom_Accel.elf
gives
text data bss dec hex filename 6036 40 1120 7196 1c1c c:\wsp_Freedom\Freedom_Accel\FLASH\Freedom_Accel.elf
Here I have the code size (text), constant data (data) and global variables or statically allocated variables (bss), all in decimal. The sum of text+data+bss is shown in dec(imal) and hex(adecimal).
Printing Code Size for gcc in Eclipse/CodeWarrior
Now while using the command line tool is nice, I want it be part of the build in Eclipse/CodeWarrior. The good news is: as shown in “S-Record Generation with gcc for ARM/Kinetis” it can be done.
In the build tool settings, I enable the ‘Print Size’ option and press the Apply button:
This enables a ‘GNU Print Size’ option group:
Now if I build my application, I get code and data size information:
Happy Sizing 🙂
Any new “intel” on when CW 10.3 will be released?
Just checked the page on, and it is there on the right side 🙂
Pingback: Tutorial: Freedom with FreeRTOS and Kinetis-L | MCU on Eclipse
Pingback: Optimizing the Kinetis gcc Startup | MCU on Eclipse
This didnt work for me, when I build its like its not executing the _size command. I also dont see the .s19 record appear.
Did you press the ‘Apply’ button? then additional panels should show up. Keep in mind that the default extension for the S19 file is .hex.
Pingback: Reducing Code Size with gcc and EWL | MCU on Eclipse
Hi Erich,
Your post is very useful. I’m using CodeWarrior 10.2 for Kinetis K60N512. How can I print code size with Codewarrior ARM toolchain?
Hello, this is only possible with gcc and MCU10.3.
Thank you 🙂 Hope next version of CW will support it
I need to disappoint you: according to Freescale, the non-gcc ARM compiler is in maintenance mode. It is still present in MCU10.3, but I would not expect any new features or enhancements for it. ARM gcc is the future. I already switched over all my Kintetis project to gcc, and the code is not only faster, it is smaller too, and the compiler/build tools have more features. No reasons for me to stay with the non gcc compiler.
Hi,
The “Additional Tools” settings seem to be removed in CW 10.3 official version. Is there any way to enable the “Print Size” option in CW 10.3 official release?
Thank you for your help.
Hi Joey,
it is still there for me in my offical MCU10.3. Keep in mind that the setting is for gcc, and *not* for the other ARM compiler (from Freescale) in MCU10.3. Maybe this is the disconnect?
Hi Erich:
Mmm… I can find it with projects that I created (and gcc was selected as compiler), but I can’t find “Additional Tools” in a MQX example project (created by selecting New MQX 3.8 project, and selected “hello” project from the example list). It seems MQX projects are still using ARM compiler, even we create it under CW 10.3.
Thank you for your response. I will inform my customers to check code size from xMap file.
PS: I am Freescale disty FAE and your blog does help me a lot. I would like to present my appreciation for your contributions on this blog.
Hi Joey,
thanks :-). For MQX-Lite (Kinetis-L) projects, gcc is used. I think the next MQX version will finally support gcc as well for the other Kinetis parts.
Hello:
First of all thank you for your hard work on your blog, I really liked it and it has helped me a lot to learn about ARMs.
I wanted to ask you about the data, bss and Text information. At the end, which one of them can tell me about FLASH and RAM usage? When I download a program to the board, what it downloads is the sum of text + data, so what is bss? I made a new barebones project and I have a huge bss data (2076).
Also, how can I know the RAM the program will use?
Thank you very much for your time,
Ed.
Hi Ed,
thank you :-).
You ask a good question. Let me see what I could write up on this subject over the week-end.
The NetBeans based tools for Microchip PIC32 show you two little fuel gauges for Flash and RAM usage. Very cool feature. The rest of the thing is nearly unusable, though. 🙂
Yes, mbed () has something similar: it shows with bar graphs the RAM/Flash usuage.
Hi Ed,
have a look here:
I hope this helps.
Pingback: text, data and bss: Code and Data Size Explained | MCU on Eclipse
in case you want to reduce bss consumption, you can modify the linker script in the heap and stack area. Afaik heap can be chosen to zero, when no malloc is used.
Hi Michael,
yes, this is indeed true. I have not optimized the linker file for things like this yet.
Thanks for pointing to this!
I had myself scratching my head and pawing my HP42S when you said “Here I have the code size (text), constant data (data) and global variables or statically allocated variables (bss), all in hexadecimal. The sum of text+data+bss is shown in dec(imal) and hex(adecimal).”
Until I realized you meant *all in decimal*, when you said “all in hexadecimal”
Hi Tim,
thanks for spotting this bug! Indeed, it should read *decimal*. I have fixed it now.
Thanks again!
No worries Erich.
Your blog is so good, and this was such a minor thing.
I’m just happy you are shedding so much light on the Freedom boards. At least for me, there is no other source of this information. I’m trying out the Freescale ARM Cortex chips after having been a Mot/Freescale person for decades, and more lately taken a few years out for other things. Just an observation about Freedom stuff, at least the K20D50 version: For a product that tries to be like Arduino….it is far from the ease of use of Arduino, and could use a lot more sample programs and drag and drop kind of applications for the un-itiated. I know this is a blog thread about finding the memory left in Codewarrior, but I wanted to get that off my chest!
Tim
Offgrid
Hi Tim,
yeah, I know what you mean, and I felt the same, so I published my findings as much as possible. I think many companies (especially silicon companies) have not realized (yet?) that the best microcontrollers are nothing without good tools and software. I mean the Arduino and Raspberry Pi are not the best microcontrollers, but having an excellent software and tools environment. And especially an open source driven environment. I belive only vendors will survive which can adopt to that change. Will see.
Erich, You are really keen on Processor Expert, and I need some help, so I thought I would write.
I’ve never used the tool, electing instead to handcraft code to get exactly what I want. Now with lots of RAM and Flash, and with the ability to use different variants easily, I find myself more interested in PE, and using it at least for startup code on different peripherals.
My dillema is that I have spent far too much time on getting a real time timer running and I could use a hand; I literally cannot get the timer to start and run. I’m using the RealTime_LDD and it’s configured to use GetTimeSec function. The help window on this component gives me this Typical Usage:
void main(void) { unsigned int i, time; float one_loop_us;
RT1_Reset(); /* reset the counter */ for (i = 0; i < 60000; ++i); /* for-cycle */
/* get measured time of whole for-cycle */ if(RT1_GetTimeUS(RT1_DeviceData,&time) == ERR_OK) { /* average time of one loop */ one_loop_us = time / 60000.0; } }
1. First off, I cannot use the RT1_Reset() function as the gcc compiler gives me "undefined reference to `RT1_Reset'" in clock.c , which seem weird since this is defined in the PE modules, and referenced in my ProcessorExpert.c file. 2. Here is my clock routine (clock.c), when single stepping in debug mode, I see that it does actually go into the RT1_GetTimeUS() function.
unsigned int seconds, minutes, hours, i; unsigned int msecTimer, time, RT1_DeviceData; //typedef uint32_t TU2_TValueType ; // Type for data parameters of methods. 32bit is maximum //long TU2_TValueType ; // Type for data parameters of methods. 32bit is maximum //int LDD_TDeviceData;
int Clock(void) { #define TICKS1SEC 100 // there are 100 – 10msec ticks in one second
if(RT1_GetTimeUS(RT1_DeviceData,&time) == 0){ msecTimer = time ; } else i = 0; //RT1_Reset(); //for (i = 0; i = TICKS1SEC){ msecTimer = 0; seconds ++; //RT1_Reset(); /* reset the real time counter */ } if (seconds >= 60) { seconds = 0; minutes ++; if (minutes >= 60) { minutes = 0; hours ++; if (hours >= 24) hours = 0; // hours go to 0 every day, 24 hours } } return (seconds); }
I do see the RT1_GetTimeUS() routine wants to return ERR_OVERFLOW when called. I’ve got both the linked timer, TimerUnit_LDD (TU2) and this RealTime_LDD resultion set to 16 bits, and resultion set to 10msecs. Initialization for RealTime is yes in init code and yes for Auto initialization, and yes in init code for the TU2 timer.
Anything you can do to get me moving again…would be most appreciated!!!
I apologize for my late response (to many things going on right now). I would need to try out the same thing you describe, but here are a few thoughts (blindly without trying it myself):
– If RT1_Reset() is not defined, it could be that it is not enabled? Check if the method has a X on it in the Components view. If yes, it is disabled. Enable it with right mouse click.
– If you are interested just in a realtime clock functionality (without the need for the RTC on the chip), you easily could use the GenericTimeDate component I have created. See. Simply import that component (see), then add a timer (e.g. 10 ms) and call the TmDt1_AddTick() from the timer interrupt. Then you have a realtime clock 🙂
I hope this helps get moving.
Thanks Erich, your tip about enabling the Reset was right on, it was disabled, and I learned a new way to talk to PE. Unfortunately, that did not fix my problem. Moving the routine to main did solve the problem, so I need to see why the routines are not working in my clock file. I’ll take a look at your clock code, but since this part has it’s own RTC, it seems smart to use the on-chip resource.
Thanks again,
Tim
Hi Tim, yes, I agree using the onboard RTC is a good thing. In my projects I used the software RTC (GenericTimeDate) or an external RTC like a Maxim DS3232.
Hi Erich,
First of all, thanks for this post, it was helpful.
After doing what you teach here, and enjoying it, I wonder if you ever had this issue:
Sometimes, I do a Build All, and because it sometimes takes 1 or 2 minutes, I start to do other things: checking my mail, going to the bathroom, … sometimes I came back to the computer 15 minutes later, and then… Do I did the Build All ???? or not ??? I don’t remember !
So, I need to go to the file .elf to check the hour/date.
Do you think there might be an easy way to have the Date and Time in the console, in the last line ?
Or, is there other place were this information is available ?
Best Regards,
Christian
Hi Christian,
Not in CodeWarrior, but in the new Eclipse Kepler with the GNU ARM Eclipse plugins ().
See the screenshot ‘Building the Project (Console Output)’ which reports date/time when the build was made.
Thanks Erich.
Hi Erich, a question that i think is in topic with the article:
If i notice that the size of the used RAM is increasing more than expected,how can i check in detail the RAM size allocate by my globals and static allocated variables?
Say that, somewhere ,i erroneously declared an array with [1000] elements instead of[100] as needed,is it possible to put it in evidence in some ordered list?
Thanks for your useful work.
Diego
Hi Diego,
I suggest that you enable the linker map file (under the linker options). This creates a text file with that information.
Unfortunately at least for GNU linker that map file is not that easy to read, but I’m sure you get to it 🙂
Erich thanks for the datailed answer on the same
question(added by more data) on Freescale forum
,unselecting the Print Link Map option everything works fine
Diego
Hi Diego,
you are welcome! Good to hear that this solves your problem 🙂
Pingback: Printing Code Size Information in Eclipse | MCU on Eclipse
Hi,
Please let me know the option to enable the memory map summary like the one in the starting of this thread. I want to know what is the total size of the .text, total size of .bss and the total size of .data. Currently I use the option -Xlinker -Map=$(basename $(1)).map to generate the map file..with Arm gcc compiler.
Best Regards
Hari
See the last screenshot of this post (“Kinetis ARM GNU gcc Code and Data Size Information with CodeWarrior”) which shows the options. You do not get that from the linker, you need to call the size program.
Hi Erich
Had to deal with memory questions and noted, that the option to put the size information to the console has not worked for me. I don’t even see a call to the size program in the console. However, using Post-build steps in Project Properties > C/C++ Build > Settings > Build Steps has helped me out. I placed
“${ARM_GNU_TOOLS_HOME}/bin/arm-none-eabi-size.exe” –format=sysv ${BuildLocation}/${BuildArtifactFileName} >> ${BuildLocation}/${BuildArtifactFileBaseName}.map
in there and from now on I get a neat memory usage table at the end of my map file.
Thought this might help some other people around here. Thank you and keep on going with this great blog!
Adrian
Hi Adrian,
thanks, I’ll do my best :-).
About your problem, it might be related to this issue
?
Took me a while to find the size option on KDS. It is in C/C++ Build -> Settings -> Toolchains instead of Tool Settings.
Yes, the most recent plugin from GNU ARM Eclipse have that option moved there.
hi Eric,
I am genrating srecord file in my project and i have print size option selected in Kenetis Design Studio.
I am trying to find the End of the Program Code.
the End of program code address calculated by looking into console screen in KDS, from below is addr(33808)+ size(234296) = 268104
section size addr
.interrupts 1024 32768
.flash_config 16 1024
.text 234296 33808
.ARM 8 268104
.init_array 4 268112
.data 5452 536806400
.m_data_1FFF0000 53792 536811852
.m_interrupts_ram 1024 536805376
.bss 129660 536865792
.stack 1024 537001984
.ARM.attributes 55 0
.debug_info 980501 0
.debug_abbrev 79454 0
.debug_aranges 17552 0
.debug_ranges 14576 0
.debug_macro 490179 0
.debug_line 611590 0
.debug_str 1977333 0
.comment 112 0
.debug_frame 56792 0
.stab 156 0
.stabstr 335 0
Total 4654935
but when I check in srec file (below shown end of file)generated by KDS. I see end address diffreent which is higher than above print
which is 0x4FEB0 -> in decimal 327344
S21404FE900000000000000000000000000000000059
S21404FEA00000000000000000000000000000000049
S21404FEB00000000000000000000000000000000039
is this generated srec is adding any dummy data in to Flash area
Hi Niranjan,
this all depends on your linker file, maybe you are using some filling with zero bytes?
Regardless, if you want to know the end of your code, then you can define a symbol in the linker file.
For example
___ROM_AT = .;
} > m_text
the ___ROM_AT symbol is what you can use in your code to find out the end of the m_text segment.
Thanks Eric
LikeLiked by 1 person | https://mcuoneclipse.com/2012/09/24/code-size-information-with-gcc-for-armkinetis/ | CC-MAIN-2017-13 | refinedweb | 2,939 | 73.78 |
React Suite is a set of react component libraries for enterprise system products. Built by HYPERS front-end team and UX team, mainly serving company's big data products.
After three major revisions, a large number of components and rich functionality have been accumulated.
UI Design
React Suite Design Prototype and specification, click to view.
Supported Platforms
Browser
React Suite supports the latest, stable releases of all major browsers and platforms. IE<=9 is no longer supported since React Suite 3.0. React Suite is designed and implemented for use on modern desktop browsers rather than mobile browsers.
Server
React Suite supports server side rendering. Support Next.js to build applications.
Supported development environment
- Supports React 16 +
- Supports TypeScript
- Supports Flow
- Supports Electron
Installation
React Suite is available as an npm package.
npm i rsuite --save
or if you prefer Yarn
yarn add rsuite
Usage
Here's a simple example
import { Button } from 'rsuite'; import 'rsuite/styles/less/index.less'; // or 'rsuite/dist/styles/rsuite.min.css' ReactDOM.render(<Button>Button</Button>, mountNode);
Live preview on CodeSandbox
Documentation
You can go through full documentation or start with following sections
Examples
- Management system
- Use modularized
- Use CDN
- Internationalization
- Themes
- Use in create-react-app
- Use in Flow
- Use in TypeScript
- Use in Next.js
Changelog
Detailed changes for each release are documented in the release notes.
Development
You can learn about our development plan through Trello and hope that you can get involved.
- Fork repo.
$ git clone [email protected]:<YOUR NAME>/rsuite.git $ cd rsuite $ npm install $ npm run dev
- Fork repo.
$ git clone [email protected]:<YOUR NAME>/rsuite.github.io.git $ cd rsuite.github.io $ npm install $ npm run dev
- Your show time. Open url in browser.
Contribution
Make sure you've read the guidelines before you start contributing.
Editor preferences are available in the .prettierrc for easy use in common code editors. Read more and download plugins at.
Supporting React Suite
If you like React Suite, you can show your support by either
- Starring this repo
- Leaving a comment here if you are using React Suite in your project (like we do 😄)
- Becoming a backer on OpenCollective
This project exists thanks to all the people who contribute.
License
React Suite is MIT licensed. Copyright (c) 2016-present, HYPERS. | https://nicedoc.io/rsuite/rsuite | CC-MAIN-2019-35 | refinedweb | 379 | 50.53 |
python-borium 0.1.0
Simple Get/Put API for the Borium Queue
Borium provides an API for the borium queue. It exposes simple get/set methods to grab and push jobs.
Borium is a simple queue system written by Kazuyoshi Tlacaelel. To learn more, visit the project repository.
Usage
import borium response = borium.put(job_type, config) # sends the job to the queue job = borium.get(job_type) # fetches a job
In both examples, job_type is a string that specifies the job that is to be enqueued. The config, though dependent on the job itself, is usually a JSON object containing the configuration needed.
All requests to the queue will return an object containing a key called status. In the case of get this can be: nothing, unparseable, error or found. In the case of put this can be: error or stored.
If the job was found, the object will also include the key “job” which includes the config string passed.
- Downloads (All Versions):
- 4 downloads in the last day
- 49 downloads in the last week
- 163 downloads in the last month
- Author: Ben Beltran
- License:
The MIT License (MIT) Copyright (c) 2014 Ben Beltr: benbeltran
- DOAP record: python-borium-0.1.0.xml | https://pypi.python.org/pypi/python-borium/0.1.0 | CC-MAIN-2015-40 | refinedweb | 203 | 65.22 |
Key Takeaways
- For better performance, modern processors predict the branch and execute the following instructions speculatively. It is a powerful optimization
- Programmers can be misled into underestimating the cost of branch mispredictions when benchmarking code with synthetic data that is either too short or too predictable. The effect of branch mispredictions can be large. Thankfully, it is often possible to avoid branches entirely.
- Rewriting your code with fewer branches leads to code that has a more consistent speed.
- Proper handling of mispredicted branches may be required to get optimal performance.
Most software code contains conditional branches. In code, they appear in if-then-else clauses, loops, and switch-case constructs. When encountering a conditional branch, the processor checks a condition and may jump to a new code path, if the branch is taken, or continue with the following instructions. Unfortunately, the processor may only know whether a jump is necessary after executing all instructions before the jump. For better performance, modern processors predict the branch and execute the following instructions speculatively. It is a powerful optimization.
There are some limitations to speculative execution, however. For example, the processor must discard the work done after the misprediction and start anew when the branch is mispredicted. Thankfully, processors are good at recognizing patterns and avoiding mispredictions, when possible. Nevertheless, some branches are intrinsically hard to predict and they may cause a performance bottleneck.
1. Branch predictors are not easily fooled
Programmers can be misled into underestimating the cost of branch mispredictions when benchmarking code with synthetic data that is either too short or too predictable. Modern processors can learn to predict thousands of branches, so a short test can fail to expose the true cost of branch mispredictions, even if the data looks random.
Let us consider an example. Suppose we want to decode hexadecimal digits made of either the decimal digits (0-9) or the letters (A-F, a-F). We want to get the corresponding integer value in the range 0 to 16. A reasonable C function for this task might look as follow:
int decode_hex(char c) { if(c >= '0' && c <= '9') return c - '0'; if(c >= 'A' && c <= 'F') return c - 'A' + 10; if(c >= 'a' && c <= 'f') return c - 'a' + 10; return -1; }
A programmer might benchmark such a function by first generating a random string. For example, in C, we might repeatedly call the rand function and select one of the possible 22 hexadecimal digits.
char hex_table[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F' }; void build_random_string(size_t length, char *answer) { for (size_t i = 0; i < length; i++) { answer[i] = hex_table[rand() % sizeof(hex_table)]; } return answer; }
Then, one could record the time it takes to decode all hexadecimal digits in the newly generated string. For good measure, a programmer might run this test several times and compute the average. Let us plot the number of mispredicted branches per hexadecimal digit for different string lengths (1000, 2000, ...) over many trials. Importantly, we reuse the same input string in all trials.
Using a standard server processor (AMD Rome), we find that for a string containing 3000 digits, the number of mispredicted branches per value falls to 0.015 (or 1.5%) after fewer than 20 trials. For a shorter string (1000 digits), the number of mispredicted branches falls even quicker, down to 0.005 after 8 trials. In other words, a standard server processor can learn to predict all the branches generated by a 1kB hexadecimal random string after fewer than 10 decoding passes.
In programming languages supported by a just-in-time compiler (such as Java or JavaScript), it is routine to repeat the benchmarks until the compiler has optimized the code: If the test is too short, even if the input is random, we are at risk of underestimating the cost of the branch mispredictions.
Similarly, running tests with synthetic data inputs, even when the data volume is large, can make it possible for the processor to predict the branches with high accuracy. Suppose instead of using a random string of digits, we use the digits generated by counting from 0 to 65536: 0x00, 0x01, ...
The branch predictor must essentially predict where the decimal digits and the alphabetical digits appear. The resulting string (0000100021003100421052106310731084219421a521b521c631d631e731f7310842 ... 8ce18ce29ce39ce4ade5ade6bde7bde8cef9cef ...) is not random, but it might take effort to predict the patterns followed by decimal digits and by alphabetical digits. Yet, using the same AMD Rome processor, we find that the number of mispredicted branches on such a string of length 131,072 is virtually zero on the first trial: 0.002 branch misprediction per byte.
2. Branch mispredictions can be expensive
The effect of branch mispredictions can be large. Let us take the data we collected over random hexadecimal strings of various sizes, and plot the number of CPU cycles per input digit against the number of mispredicted branches. We find that the number of CPU cycles varies between slightly over 5 cycles per hexadecimal digit all the way to over 20 cycles per digit, depending on the number of mispredicted branches.
Yet, we should not conclude that the presence of a large number of mispredicted branches is necessarily a concern because there might be more pressing concerns. For example, consider a binary search in a large array. The limitation is the latency of memory access in main memory which is far more expensive than a branch misprediction.
3. Avoiding branches
Performance analysis tools, like perf (Linux), xperf (Windows), and Instruments (macOS), can measure the number of mispredicted branches. What if you have determined that for the problem at hand, branches are a problem?
Thankfully, it is often possible to avoid branches entirely. For example, to decode hexadecimal digits, we might use a single lookup in an array:
int digittoval[256] = { , 2, 3, 4, 5, 6, 7, 8, 9, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 10, 11, 12, 13, 14, 15, -1,...}; int hex(unsigned char c) { return digittoval[c]; }
This function may get compiled to a single instruction, with no branching. It can still be used to validate improper inputs by checking for a negative integers.
Thus, we can often replace branching by memorization: In effect, we precompute the branches and store them in a simple data structure like an array.
Another strategy to avoid branches is to do speculative work and to later throw it away. For example, suppose that we want to erase all negative integers from an input array of integers. In C, we might proceed with a loop and a branch:
for(size_t i = 0; i < length; i++) { if(values[i] >= 0) { values[pos++] = values[i]; } }
Let us call this function "branchy." This code checks the sign of the input and conditionally copies it to a new location. If we expect that it is difficult to predict which of the integers are negative, then it might be inefficient code. Instead, we could optimistically write out the input, but only increment our index if the integer is negative.
Thankfully, we can determine the sign of an integer without branching. Most compilers will compile the following C function into a negation followed by a logical right shift:
size_t sign(int v) { return (v >= 0 ? 1 : 0); }
Thus, we have the following function to omit negative values from an array. With most compilers, this function will contain a single branch, having to do with the loop, but it is a predictable branch for large arrays.
for(size_t i = 0; i < length; i++) { values[pos] = values[i]; pos += sign(values[i]); }
Let us call this function "branchless." Observe that both functions are not strictly equivalent. The branchy version may never write to the input array, whereas the branchless version will always write each input integer once. Thus, it may be difficult for a compiler to replace one for the other. Yet, the functions may be logically equivalent for practical purposes—an assessment best done by the programmer.
Even when it is impossible to remove all branches, reducing the number of branches "almost always taken" or "almost never taken" may help the processor better predict the remaining branches. For example, if we are decoding the digits one-by-one using a loop, then we have one predictable branch resulting from the loop per digit.
for (i = 0; i < length; i++) { int code = decode_hex(input[i]); ...
For long input strings, we can reduce by half this number of predictable branches by "unrolling" the loop: We process two input characters with each iteration of the loop.
for (; i + 1 < length; i += 2) {: int code1 = decode_hex(input[i]); int code2 = decode_hex(input[i + 1]); ...
If we count the number of mispredicted branches per input digit, we find that the unrolled version may have fewer mispredicted branches. On an AMD Rome processor with input strings made of 5000 digits, we find that after many trials the number of mispredicted branches per input digit is 0.230 for the simple loop and only 0.165 for the unrolled loop—a 30% reduction.
A possible simplified explanation for this phenomenon is that processors use the history of recent branches to predict future branches. Uninformative branches may reduce the ability of the processors to make good predictions.
When it is not possible to avoid hard-to-predict branches, we can often reduce their number. For example, when comparing two dates, it is convenient to put them in the YYYYMMDD format, and to compare the resulting 8-byte strings as if they were 64-bit integers, using a single instruction.
Conclusion
Benchmarking code containing hard-to-predict branches is difficult and programmers can sometimes underestimate the price of branches. Rewriting your code with fewer branches leads to code that has a more consistent speed. Proper handling of mispredicted branches may be required to get optimal performance.
About the Author
Daniel Lemire is a computer science professor at the Université du Québec (TELUQ). He has written over 70 peer-reviewed publications, including more than 40 journal articles. He serves on the program committees of leading computer science conferences. During the 2016-2017 NSERC Discovery Grant competition, he received a rating of outstanding for the excellence of the researcher.
Inspired by this content? Write for InfoQ.
Becoming an editor for InfoQ was one of the best decisions of my career. It has challenged me and helped me grow in so many ways. We'd love to have more people join our team.
Community comments | https://www.infoq.com/articles/making-code-faster-taming-branches/?utm_campaign=infoq_content&utm_source=infoq&utm_medium=feed&utm_term=global | CC-MAIN-2022-40 | refinedweb | 1,781 | 53 |
I'd like to define some functions for a program in another file as they are too long..
So, I used
but the problem comes here is that ...but the problem comes here is that ...PHP Code:
# include <filename.c>
The variables that I commonly used in main and this files have to be declared before I write main()..
something like:
Is this the right way to do.Is this the right way to do.Code:int variable; declared above the whole code.. # include <stdio.h> int main() { int a,b,c; .... }
I don't know whether it totally works or not.. as I am in the middle of my code. As far as I recognized is that .. its not showing the respective error.
1. If I want to define functions in some other files and include in main..
how do I do it ?
2. Actually, my function files are not located in default location..
so, I need to mention the address too..
is there any other way to do that..is there any other way to do that..PHP Code:
# include </home/username/folder/filename.c>
what I should do .. so that I need not mention this address.
something like adding search directory to the gcc compiler for checking filess.. | http://cboard.cprogramming.com/c-programming/140146-define-functions-another-file.html | CC-MAIN-2013-48 | refinedweb | 211 | 88.23 |
This Tutorial Explains what is Merge Sort in Java, MergeSort Algorithm, Pseudo Code, Merge Sort Implementation, Examples of Iterative & Recursive MergeSort:
Merge sort technique uses a “Divide-and-Conquer” strategy. In this technique, the data set that is to be sorted is divided into smaller units to sort it.
=> Read Through The Easy Java Training Series.
What You Will Learn:
Merge Sort In Java
For example, if an array is to be sorted using mergesort, then the array is divided around its middle element into two sub-arrays. These two sub-arrays are further divided into smaller units until we have only 1 element per unit.
Once the division is done, this technique merges these individual units by comparing each element and sorting them when merging. This way by the time the entire array is merged back, we get a sorted array.
In this tutorial, we will discuss all the details of this sorting technique in general including its algorithm and pseudo codes as well as the implementation of the technique in Java.
MergeSort Algorithm In Java
Following is the algorithm for the technique.
#1) Declare an array myArray of length N
#2) Check if N=1, myArray is already sorted
#3) If N is greater than 1,
- set left = 0, right = N-1
- compute middle = (left + right)/2
- Call subroutine merge_sort (myArray,left,middle) => this sorts first half of the array
- Call subroutine merge_sort (myArray,middle+1,right) => this will sort the second half of the array
- Call subroutine merge (myArray, left, middle, right) to merge arrays sorted in the above steps.
#4) Exit
As seen in the algorithm steps, the array is divided into two in the middle. Then we recursively sort the left half of the array and then the right half. Once we individually sort both the halves, they are merged together to obtain a sorted array.
Merge Sort Pseudo Code
Let’s see the pseudo-code for the Mergesort technique. As already discussed since this is a ‘divide-and-conquer’ technique, we will present the routines for dividing the data set and then merging the sorted data sets.
procedure mergesort( var intarray as array ) if ( n == 1 ) return intarray var lArray as array = intarray[0] ... intarray [n/2] var rArray as array = intarray [n/2+1] ... intarray [n] lArray = mergesort(lArray ) rArray = mergesort(rArray ) return merge(lArray, rArray ) end procedure procedure merge( var l_array as array, var r_array as array ) var result as array while (l_array and r_array have elements ) if (l_array [0] > r_array [0] ) add r_array [0] to the end of result remove r_array [0] from r_array else add l_array [0] to the end of result remove l_array [0] from l_array end if end while while (l_array has elements ) add l_array [0] to the end of result remove l_array [0] from l_array end while while (r_array has elements ) add r_array [0] to the end of result remove r_array [0] from r_array end while return result end procedure
In the above pseudo-code, we have two routines i.e. Mergesort and merge. The routine Mergesort splits the input array into an individual array that is easy enough to sort. Then it calls the merge routine.
The merge routine merges the individual sub-arrays and returns a resultant sorted array. Having seen the algorithm and pseudo-code for Merge sort, let’s now illustrate this technique using an example.
MergeSort Illustration
Consider the following array that is to be sorted using this technique.
Now according to the Merge sort algorithm, we will split this array at its mid element into two sub-arrays. Then we will continue splitting the sub-arrays into smaller arrays till we get a single element in each array.
Once each sub-array has only one element in it, we merge the elements. While merging, we compare the elements and ensure that they are in order in the merged array. So we work our way up to get a merged array that is sorted.
The process is shown below:
As shown in the above illustration, we see that the array is divided repeatedly and then merged to get a sorted array. With this concept in mind, let’s move onto the implementation of Mergesort in Java programming language.
Merge Sort Implementation In Java
We can implement the technique in Java using two approaches.
Iterative Merge Sort
This is a bottom-up approach. The sub-arrays of one element each are sorted and merged to form two-element arrays. These arrays are then merged to form four-element arrays and so on. This way the sorted array is built by going upwards.
The below Java example shows the iterative Merge Sort technique.
import java.util.Arrays; class Main { // merge arrays : intArray[start...mid] and intArray[mid+1...end] public static void merge(int[] intArray, int[] temp, int start, int mid, int end) { int k = start, i = start, j = mid + 1; // traverse through elements of left and right arrays while (i <= mid && j <= end) { if (intArray[i] < intArray[j]) { temp[k++] = intArray[i++]; } else { temp[k++] = intArray[j++]; } } // Copy remaining elements while (i <= mid) { temp[k++] = intArray[i++]; } // copy temp array back to the original array to reflect sorted order for (i = start; i <= end; i++) { intArray[i] = temp[i]; } } // sorting intArray[low...high] using iterative approach public static void mergeSort(int[] intArray) { int low = 0; int high = intArray.length - 1; // sort array intArray[] using temporary array temp int[] temp = Arrays.copyOf(intArray, intArray.length); // divide the array into blocks of size m // m = [1, 2, 4, 8, 16...] for (int m = 1; m <= high - low; m = 2*m) { for (int i = low; i < high; i += 2*m) { int start = i; int mid = i + m - 1; int end = Integer.min(i + 2 * m - 1, high); //call merge routine to merge the arrays merge(intArray, temp, start, mid, end); } } } public static void main(String[] args) { //define array to be sorted int[] intArray = { 10,23,-11,54,2,9,-10,45 }; //print the original array System.out.println("Original Array : " + Arrays.toString(intArray)); //call mergeSort routine mergeSort(intArray); //print the sorted array System.out.println("Sorted Array : " + Arrays.toString(intArray)); } }
Output:
Original Array : [10, 23, -11, 54, 2, 9, -10, 45]
Sorted Array : [-11, -10, 2, 9, 10, 23, 45, 54]
Recursive Merge Sort
This is a top-down approach. In this approach, the array to be sorted is broken down into smaller arrays until each array contains only one element. Then the sorting becomes easy to implement.
The following Java code implements the recursive approach of the Merge sort technique.
import java.util.Arrays; public class Main { public static void merge_Sort(int[] numArray) { //return if array is empty if(numArray == null) { return; } if(numArray.length > 1) { int mid = numArray.length / 2; //find mid of the array // left half of the array int[] left = new int[mid]; for(int i = 0; i < mid; i++) { left[i] = numArray[i]; } // right half of the array int[] right = new int[numArray.length - mid]; for(int i = mid; i < numArray.length; i++) { right[i - mid] = numArray[i]; } merge_Sort(left); //call merge_Sort routine for left half of the array merge_Sort(right); // call merge_Sort routine for right half of the array int i = 0; int j = 0; int k = 0; // now merge two arrays while(i < left.length && j < right.length) { if(left[i] < right[j]) { numArray[k] = left[i]; i++; } else { numArray[k] = right[j]; j++; } k++; } // remaining elements while(i < left.length) { numArray[k] = left[i]; i++; k++; } while(j < right.length) { numArray[k] = right[j]; j++; k++; } } } public static void main(String[] args) { int numArray[] = {10, 23, -11, 54, 2, 9, -10, 45}; int i=0; //print original array System.out.println("Original Array:" + Arrays.toString(numArray)); //call merge_Sort routine to sort arrays recursively merge_Sort(numArray); //print the sorted array System.out.println("Sorted array:" + Arrays.toString(numArray)); } }
Output:
Original Array:[10, 23, -11, 54, 2, 9, -10, 45]
Sorted array:[-11, -10, 2, 9, 10, 23, 45, 54]
In the next section, let’s switch from arrays and use the technique to sort the linked list and array list data structures.
Sort Linked List Using Merge Sort In Java
Mergesort technique is the most preferred one for sorting linked lists. Other sorting techniques perform poorly when it comes to the linked list because of its mostly sequential access.
The following program sorts a linked list using this technique.
import java.util.*; // A singly linked list node class Node { int data; Node next; Node(int data, Node next) { this.data = data; this.next = next; } }; class Main { //two sorted linked list are merged together to form one sorted linked list public static Node Sorted_MergeSort(Node node1, Node node2) { //return other list if one is null if (node1 == null) return node2; else if (node2 == null) return node1; Node result; // Pick either node1 or node2, and recur if (node1.data <= node2.data) { result = node1; result.next = Sorted_MergeSort(node1.next, node2); } else { result = node2; result.next = Sorted_MergeSort(node1, node2.next); } return result; } //splits the given linked list into two halves public static Node[] FrontBackSplit(Node source) { // empty list if (source == null || source.next == null) { return new Node[]{ source, null } ; } Node slow_ptr = source; Node fast_ptr = source.next; // Advance 'fast' two nodes, and advance 'slow' one node while (fast_ptr != null) { fast_ptr = fast_ptr.next; if (fast_ptr != null) { slow_ptr = slow_ptr.next; fast_ptr = fast_ptr.next; } } // split the list at slow_ptr just before mid Node[] l_list = new Node[]{ source, slow_ptr.next }; slow_ptr.next = null; return l_list; } // use Merge sort technique to sort the linked list public static Node Merge_Sort(Node head) { // list is empty or has single node if (head == null || head.next == null) { return head; } // Split head into 'left' and 'right' sublists Node[] l_list = FrontBackSplit(head); Node left = l_list[0]; Node right = l_list[1]; // Recursively sort the sublists left = Merge_Sort(left); right = Merge_Sort(right); // merge the sorted sublists return Sorted_MergeSort(left, right); } // function to print nodes of given linked list public static void printNode(Node head) { Node node_ptr = head; while (node_ptr != null) { System.out.print(node_ptr.data + " -> "); node_ptr = node_ptr.next; } System.out.println("null"); } public static void main(String[] args) { // input linked list int[] l_list = { 4,1,6,2,7,3,8 }; Node head = null; for (int key: l_list) { head = new Node(key, head); } //print the original list System.out.println("Original Linked List: "); printNode(head); // sort the list head = Merge_Sort(head); // print the sorted list System.out.println("\nSorted Linked List:"); printNode(head); } }
Output:
Original Linked List:
8 -> 3 -> 7 -> 2 -> 6 -> 1 -> 4 -> null
Sorted Linked List:
1 -> 2 -> 3 -> 4 -> 6 -> 7 -> 8 -> null
Sort ArrayList Using Merge Sort In Java
Like Arrays and Linked lists, we can also use this technique for sorting an ArrayList. We will use similar routines to divide the ArrayList recursively and then merge the sublists.
The below Java code implements the Merge sort technique for ArrayList.
import java.util.ArrayList; class Main { //splits arrayList into sub lists. public static void merge_Sort(ArrayList<Integer> numList){ int mid; ArrayList<Integer> left = new ArrayList<>(); ArrayList<Integer> right = new ArrayList<>(); if (numList.size() > 1) { mid = numList.size() / 2; // left sublist for (int i = 0; i < mid; i++) left.add(numList.get(i)); //right sublist for (int j = mid; j < numList.size(); j++) right.add(numList.get(j)); //recursively call merge_Sort for left and right sublists merge_Sort(left); merge_Sort(right); //now merge both arrays merge(numList, left, right); } } private static void merge(ArrayList<Integer> numList, ArrayList<Integer> left, ArrayList<Integer> right){ //temporary arraylist to build the merged list ArrayList<Integer> temp = new ArrayList<>(); //initial indices for lists int numbersIndex = 0; int leftIndex = 0; int rightIndex = 0; //traverse left and righ lists for merging while (leftIndex < left.size() && rightIndex < right.size()) { if (left.get(leftIndex) < right.get(rightIndex) ) { numList.set(numbersIndex, left.get(leftIndex)); leftIndex++; } else { numList.set(numbersIndex, right.get(rightIndex)); rightIndex++; } numbersIndex++; } //copy remaining elements from both lists, if any. int tempIndex = 0; if (leftIndex >= left.size()) { temp = right; tempIndex = rightIndex; } else { temp = left; tempIndex = leftIndex; } for (int i = tempIndex; i < temp.size(); i++) { numList.set(numbersIndex, temp.get(i)); numbersIndex++; } } public static void main(String[] args) { //declare an ArrayList ArrayList<Integer> numList = new ArrayList<>(); int temp; //populate the ArrayList with random numbers for (int i = 1; i <= 9; i++) numList.add( (int)(Math.random() * 50 + 1) ); //print original ArrayList of random numbers System.out.println("Original ArrayList:"); for(int val: numList) System.out.print(val + " "); //call merge_Sort routine merge_Sort(numList); //print the sorted ArrayList System.out.println("\nSorted ArrayList:"); for(int ele: numList) System.out.print(ele + " "); System.out.println(); } }
Output:
Original ArrayList:
17 40 36 7 6 23 35 2 38
Sorted ArrayList:
2 6 7 17 23 35 36 38 40
Frequently Asked Questions
Q #1) Can Merge sort be done without Recursion?
Answer: Yes. We can perform a non-recursive Merge sort called ‘iterative Merge sort’. This is a bottom-up approach that begins by merging sub-arrays with a single element into a sub-array of two elements.
Then these 2-element sub-arrays are merged into 4-element sub arrays and so on using iterative constructs. This process continues until we have a sorted array.
Q #2) Can Merge sort be done in place?
Answer: Merge sort generally is not in-place. But we can make it in-place by using some clever implementation. For example, by storing two elements value at one position. This can be extracted afterward using modulus and division.
Q #3) What is a 3 way Merge sort?
Answer: The technique we have seen above is a 2-way Merge sort wherein we split the array to be sorted into two parts. Then we sort and merge the array.
In a 3-way Merge sort, instead of splitting the array into 2 parts, we split it into 3 parts, then sort and finally merge it.
Q #4) What is the time complexity of Mergesort?
Answer: The overall time complexity of Merge sort in all cases is O (nlogn).
Q #5) Where is the Merge sort used?
Answer: It is mostly used in sorting the linked list in O (nlogn) time. It is also used in distributed scenarios wherein new data comes in the system before or post sorting. This is also used in various database scenarios.
Conclusion
Merge sort is a stable sort and is performed by first splitting the data set repeatedly into subsets and then sorting and merging these subsets to form a sorted data set. The data set is split until each data set is trivial and easy to sort.
We have seen the recursive and iterative approaches to the sorting technique. We have also discussed the sorting of Linked List and ArrayList data structure using Mergesort.
We will continue with the discussion of more sorting techniques in our upcoming tutorials. Stay Tuned!
=> Visit Here For The Exclusive Java Training Tutorial Series. | https://www.softwaretestinghelp.com/merge-sort-java/ | CC-MAIN-2021-17 | refinedweb | 2,472 | 54.93 |
This module provides access to the Zerynth App functionalities.
The Zerynth App is designed to make interaction with Zerynth programs on your microcontroller device easy. You can think of a Zerynth App as a bidirectional communication channel between a Zerynth script running on the microcontroller and some HTML+Javascript running as a mobile app. In conventional client/server network terms the microcontroller device would be the server, responding to requests from the mobile app client.
A program using the Zerynthapp module must provide the following components:
- a user interface template, which the microcontroller device delivers to the mobile client
- a set of notifications that the microcontroller device can send to the mobile app, where they are handled as events by scripts embedded in the template
- a set of event functions that run on the microcontroller device in response to messages receieved from the mobile client
An instance of the Python ZerynthApp class defined in this module, when instantiated and run on your device, waits for messages coming from the mobile app via wifi (bluetooth LE is currently under development). Each valid message becomes an event to be processed by its nominated function.
ZerynthApp Step by Step¶
Using the Python zerynthapp module is easy.
- First, define an html template by adding a new html file to the current project. Declare the template as a resource so you can save it to your device’s flash memory and open it in the script.
- Create a ZerynthaApp instance with a name and a description.
- Configure the instance, linking event names to the functions that handle them.
- Call the zerynthapp instance’s
runmethod.
HTML templates¶
An HTML template defines the content that will be delivered to the mobile app, where it is rendered. Embedded Javascript adds event handling logic to the template. The ZerynthApp Javascript object can remotely call Python functions by name to be executed on the microcontroller device.
The example below will help you to understand the structure of a template:
<html> <head> <zerynth/> <zerynth-jquery/> <zerynth-jquery-mobile/> <meta name="viewport" content="width=device-width, initial-scale=1"> </head> <body> <div data- <div data-<h1>Zerynth Test App</h1></div> <div role="main" class="ui-content" style="text-align:center"> <button class="ui-btn ui-btn-inline" onclick="ZerynthApp.call('showmsg','Random number for you:'+Math.random())">Click me!</button> <p id="label"></p> </div> <div data-Powered by Zerynth</div> </div> <script> function update_label(msg){ $("#label").text(msg) } ZerynthApp.listen("btn",update_label) ZerynthApp.jquerymobile_scalecontent() </script> </body> </html>
The following special tags in the head section import javascript libraries embedded in the mobile app:
- <zerynth/> imports the basic Zerynth functionalities
- <zerynth-jquery/> imports the JQuery library
- <zerynth-jquery-mobile/> imports the JQuery Mobile library
- <zerynth-jqwidgets/> imports the JQWidgets library
The body section consists of a <div> defining the appearance of the interface, and scripting to handle interactions with the device.
In this instance the top-level <div> contains three further <div> elements for the app header, main window and footer. The onclick attribute of the button specifies generation of an event called showmsg, using a call to the ZerynthApp’s call method. All the parameters are encoded, sent to the board, and used as arguments of the Python function linked to the show_message event. The ZerynthApp.call method is the channel from Javascript to Python
In the final script section the ZerynthApp Javascript object is used to register a notification name “btn”. Everytime the microcontroller device sends a notification with that name the update_label JavaScript function will be executed (in this case it changes the text of the <p> html element whose id is “label”). Parameters can be passed to the notify function and will be transmitted to the mobile app. The notify method of the ZerynthApp instance is the channel from Python to Javascript.
Zerynth App Instances¶
An HTML template must be coupled with a Zerynth script running on a microcontroller. Here is an example script that works with the template above:
import streams from wireless import wifi from cc3000 import cc3000_tiny as cc3000 from zerynthapp import zerynthapp streams.serial() new_resource("template.html") try: cc3000.auto_init() print("Establishing Link...") wifi.link("Network Name", wifi.WIFI_WPA2,"WIFI-Password") print("Network OK!") except Exception as e: print(e) def show_message(msg): print(msg) pressed = 0 def btn_pressed(): global pressed pressed+=1 vp.notify("btn", "Board button pressed ["+str(pressed)+"] times") onPinFall(BTN0, btn_pressed) # configure and start the zerynthapp vp = zerynthapp.ZerynthApp("Test", "Test Object", "resource://template.html") vp.on("showmsg",show_message) vp.run()
This simple script connects to the local Wifi network, configures and runs a ZerynthApp instance. First of all, the template must be saved to flash by calling the function new_resource. It can then be referenced with the url “resource://name-of-file.extension”. The script defines two functions and creates a ZerynthApp instance, passing the name of the object, its description and the url of the resource it created to the template. The ZerynthApp object’s on method configures the Javascript-to-Python channel: everytime a “showmsg” event is sent from Javascript, the function show_message is called in the Zerynth script. The onPinFall call establishes that each time the board’s button is pressed the btn_pressed function is called, and sends the event “btn” to the mobile app using the ZerynthApp’s notify method. The mobile app is listening for these events, and each time it receives such an event it calls the update_label function.
Object discovery, template transfer and object-to-mobile-app linking is automatically handled by the ZerynthApp instance.
Finally, more than one ZerynthApp instance can be created in the same Zerynth script.
The ZerynthApp class¶
- class
ZerynthApp(name, desc, template, logging=False)¶
Create a ZerynthApp instance named name, with short description desc and with UI template template If logging is True, some debug messages are printed.
template must be the url of some resource that can be opened with the open builtin.
notify(what, value)¶
Send the message named what with value value to the mobile app. Notifications are not sent if the mobile app is not linked (i.e. has not yet received the UI template). | https://docs.zerynth.com/latest/official/lib.zerynth.zerynthapp/docs/zerynthapp.html | CC-MAIN-2019-30 | refinedweb | 1,023 | 52.29 |
std::regex_search
From cppreference.com
Determines if there is a match between the regular expression
e and some subsequence in the target character sequence.
1) Analyzes generic range
[first,last). Match results are returned in
m.
2) Analyzes a null-terminated string pointed to by
str. Match results are returned in
m.
3) Analyzes a string
s. Match results are returned in
m.
4-6) Equivalent to (1-3), just omits the match results.
7) The overload 3 is prohibited from accepting temporary strings, otherwise this function populates match_results m with string iterators that become invalid immediately.
regex_search will successfully match any subsequence of the given sequence, whereas std::regex_match will only return true if the regular expression matches the entire sequence.
[edit] Parameters
[edit] Return value
Returns true if a match exists, false otherwise. In either case, the object
m is updated, as follows:
If the match does not exist:
If the match exists:
[edit] Example
Run this code
#include <iostream> #include <string> #include <regex> int main() { std::string lines[] = {"Roses are #ff0000", "violets are #0000ff", "all of my base are belong to you"}; std::regex color_regex("#([a-f0-9]{2})" "([a-f0-9]{2})" "([a-f0-9]{2})"); for (const auto &line : lines) { std::cout << line << ": " << std::regex_search(line, color_regex) << '\n'; } std::smatch color_match; for (const auto &line : lines) { std::regex_search(line, color_match, color_regex); std::cout << "matches for '" << line << "'\n"; for (size_t i = 0; i < color_match.size(); ++i) { std::ssub_match sub_match = color_match[i]; std::string sub_match_str = sub_match.str(); std::cout << i << ": " << sub_match_str << '\n'; } } }
Output:
Roses are #ff0000: 1 violets are #0000ff: 1 all of my base are belong to you: 0 matches for 'Roses are #ff0000' 0: #ff0000 1: ff 2: 00 3: 00 matches for 'violets are #0000ff' 0: #0000ff 1: 00 2: 00 3: ff matches for 'all of my base are belong to you' | http://en.cppreference.com/w/cpp/regex/regex_search | CC-MAIN-2014-41 | refinedweb | 309 | 52.7 |
Using Genetic Algorithms To Do Portfolio Optimisation
In this approach, I will be talking about a problem posted on the Auquan website. Go here to view the problem and code along: quant-quest.auquan.com/competitions/uk-data-science-varsity
If you want to get more detail on the deap implementation head to:
Introduction
There are many ways to solve optimisation problems and this is by no means the best or easiest way. Evolutionary algorithms are typically used to provide good approximate solutions to problems that cannot be solved easily using other techniques. Given that this problem has some difficult constraints, this is an approach that would be useful in generating an initial answer.
In general, for any optimization problem where the solution space we are searching isn’t easy to understand or has complex boundaries with many constraints, EA’s may provide good results. This does still require that we are able to develop an effective EA representation of that space.
The problem presented in the Global Recruiting Competition (see above) has many constraints and it’s difficult to understand how that affects the solution space, we will try solving it using an evolutionary algorithm-based approach.
If you are earlier in your data science journey, before you read this article you may want to look at a few articles on EAs.
-
-
Creating a Solution
Imports
We first get the required modules for our approach, we will use deap for EA implementation. (Learn more about deap: Paper | Github)
randomgives us a way to generate random bits;
deapthis implements the functionality for evolutionary algorithms in python, we'll use the following submodules
basegives us access to the Toolbox and base Fitness;
creatorallows us to create our types;
toolsgrants us access to the operators bank;
algorithmsenables us some ready generic evolutionary loops.
import randomfrom deap import base, creator, tools, algorithms
We are going to try to get the optimal weights for only a single date, but this approach should work for any date in the problem dataset. I am using the optimisation parameters directly from pickle files.
import pickle("ri", "Dt", "St" and "wi" refer to features of the supplied dataset - see the problem description for details)f = open("ri.pickle","rb") ## predicted returns for this dateri = pickle.load(f)f = open("Dt.pickle","rb") ## Duration values for assetsDt = pickle.load(f)f = open("St.pickle","rb") ## Spread values for assetsSt = pickle.load(f)f = open("wi.pickle","rb") ## weights in the index for assetswi = pickle.load(f)f.close()
Type Creation
First step with deap is to create the types we are going to need for our algorithm. Usually, the types created are ‘the fitness’ and ‘the individual’. For this particular problem, we want to create a portfolio with the best returns possible. Thus we need a list of real numbers for weights and our fitness would be just the net returns (adjusted for penalties for voilating constraints).
Type creation is done by calling the function
create in the creator module. This function takes two mandatory arguments and additional optional arguments. The first argument is the actual name of the type that we want to create. The second argument is the base class that the new type created should inherit from. Finally, the optional arguments are members to add to the new type. For a detailed understanding of deap types, check out this.. (We are using FitnessMax because we want to maximise returns, if this was a minimisation problem we would use FitnessMin).
The classes we have created are made available in the creator module. We can directly instantiate objects of each class as follows:
ind = creator.Individual([1, 0, 1, 1, 0]) ## create an individual with these weightsprint(ind)print(type(ind))print(type(ind.fitness))
Initialising the individual and population
An individual in the sense of evolutionary algorithms is just a set of weights. A population is just a set of multiple individuals. The goal is to find the best individual as the population evolves and the best individual is defined on the basis of fitness.
The toolbox class in deap is intended to store functions with their arguments for evolving the population. We can register a function with two mandatory arguments, the alias to give to the function and the function it will be associated with. Any additional arguments can be given as an argument when the alias is called.
toolbox = base.Toolbox()toolbox.register("attr_bool", random.random)toolbox.register("individual", tools.initRepeat, creator.Individual, toolbox.attr_bool, n=len(ri))toolbox.register("population", tools.initRepeat, list, toolbox.individual)
In this last block of code, we created a toolbox object and registered three functions:
- This first one
attr_boolcreates a random real number in the interval [0,1][0,1] by using random we imported earlier.
- The second function
individualwill use the initRepeat function (from the deap toolbox) to fill an
Individualclass with what is produced by repeated calls to the previously defined
attr_boolfunction, this basically initialises the weights for a random portfolio.
- The final one does the same thing for the
populationfunction, which initialises our population.
For example, calling every function individually shows how it proceeds.
bit = toolbox.attr_bool()ind = toolbox.individual()pop = toolbox.population(n=500)print("bit is of type %s\n" % (type(bit)))print("ind is of type %s and contains %d bits\n" % (type(ind), len(ind)))print("pop is of type %s and contains %d individuals\n" % (type(pop), len(pop)))
Evaluation Function
In genetic algorithms, the evaluation function is where all the magic happens. This is the function that is used to define the fitness of an individual, this is where we define our objective. In the cell below we define our objective as the returns. We also apply penalties for voilating any constraints (These are defined in the problem copy).In this walkthrough, we have only made simple duration and spread constraints — it’s up to you to make the rest!
Although the function below doesn’t have all the constraints implemented, it should be easy enough for you to do the rest. The good thing about evolutionary algorithms is that we don’t have to worry about things like gradients and hessian calculation, so we can have non-differentiable objective functions and we can have things like step functions. One example of this would be applying a very high penalty when a very important constraint is violated. For instance, in this setup, a penalty of 10000 would be very high and would almost certainly mean that the individual would not survive to the next generation. These are sometimes also called death penalties.
If you do decide to use an EA approach, your main task is to come up with this evaluation function to make sure the constraints are satisfied at least 80% of the time while maximising returns.
weight1 = 10 ## these are the penalty weights I use for our objective function, this is for spreadweight2 = 10 ## this is for durationdef evalPortfolio(individual, St = St, wi = wi, ri = ri, Dt = Dt):import numpy as npobjective = np.dot(individual,ri) ## calculating returnsif ((np.dot(St,individual)/np.dot(St,wi))-1) >0 : ## if the spread constraint is violated add a penaltyobjective = objective - weight1*((np.dot(St,individual)/np.dot(St,wi))-1) #### The above code subtracts the penalty from the fitness value,## the higher the violation the more unfit the individual will be, we can use the values of weight1## and weight2 to specify what constraint we value more. For example, if I keep weight1 as 10 but increase## weight2 to 100 that will penalize the violations for duration constraint moreif ((np.dot(Dt,individual)/np.dot(Dt,wi))-1) >0 : ## if the Duration constraint is violated add a penaltyobjective = objective - weight2*((np.dot(Dt,individual)/np.dot(Dt,wi))-1)return objective,
Genetic Operators
These are the operators that are used to evolve the population. If you want to learn how these work, look at the articles on EA’s above.
Registering the operators and their default arguments in the toolbox is done as follows.
toolbox.register("evaluate", evalPortfolio)toolbox.register("mate", tools.cxTwoPoint)toolbox.register("mutate", tools.mutFlipBit, indpb=0.10)toolbox.register("select", tools.selTournament, tournsize=3)
(If you don’t want to go into details of how the population is evolved, you can skip this section.)
The evaluation is given the alias
evaluate. As this doesn't have any other arguments apart from the individual itself we don't need to add anything. The two points crossover function is registered the same way under the alias
mate. We’re just going to use the predefined function from deap toolbox.
The mutation, for its part, needs an argument to be fixed (the independent probability of each attribute to be mutated
indpb). Finally, the selection operator is registered under the name
select and the size of the tournament set to 3.
We can, for example, mutate an individual and expect 10% of its attributes to be flipped.
ind = toolbox.individual()print(ind)print("\n")toolbox.mutate(ind)print(ind).17496858916582325, 0.058915574639683554, 0.05282789654984488, 0.14229041732505954, 0.47347302527629187, 0.4239547330119139, 0.6261109729805046, 0.03632821035165801,.27176574523503405,.6522269482319345, 0.38467801110472155, 0.7580278230001196, 0.01960680567661144, 0.7210372348101194, 0.7802174779644195, 0.9636268112795919, 0.3704593418242361,]vs..0, 0.058915574639683554, 0.05282789654984488, 0.14229041732505954, 0.47347302527629187, 0.4239547330119139, 0.0, 0.0,.0,.0, 0.38467801110472155, 0.7580278230001196, 0.01960680567661144, 0.7210372348101194, 0.0, 0.9636268112795919, 0.0,]
Evolving the Population
We evolve the population in the below function (main). It works by generating a population and giving it to the algorithm to be evolved. We are also going to employ some helpful introspection tools such as Statistics and a Hall of Fame. The Statistics object keeps tracks of various statistics of the population (as you’d expect), and the hall of fame keeps track of the best individuals that appear during the evolution. Once the evolution is finished the population contains the individuals from the last generation.
def main():import numpypop = toolbox.population(n=5000)hof = tools.HallOfFame(1)stats = tools.Statistics(lambda ind: ind.fitness.values)stats.register("avg", numpy.mean)stats.register("min", numpy.min)stats.register("max", numpy.max)pop, logbook = algorithms.eaSimple(pop, toolbox, cxpb=0.5, mutpb=0.2, ngen=100, stats=stats, halloffame=hof, verbose=True)return pop, logbook, hof
Next, we call our main fucntion and launch the evolution, the verbose argument tells it to output the stats on every generation. We can print and plot the data returned.
if __name__ == "__main__":pop, log, hof = main()print("Best individual is: %s\nwith fitness: %s" % (hof[0], hof[0].fitness))import matplotlib.pyplot as pltgen, avg, min_, max_ = log.select("gen", "avg", "min", "max")plt.plot(gen, avg, label="average")plt.plot(gen, min_, label="minimum")plt.plot(gen, max_, label="maximum")plt.xlabel("Generation")plt.ylabel("Fitness")plt.legend(loc="lower right")plt.show()gen nevals avg min max
0 5000 -1594.87 -1925.37 -1223.06
1 2990 -1474.65 -1809.43 -944.361
2 3002 -1359.97 -1703.98 -910.383
3 3075 -1249.51 -1538.01 -824.059
4 2972 -1149.89 -1489.25 -727.176
5 2981 -1060.2 -1382.69 -697.436
6 3023 -979.424 -1275.18 -646.055
7 2913 -908.14 -1259.83 -587.995
8 3002 -845.091 -1211.8 -542.399
9 2948 -785.046 -1168.46 -477.571
10 3025 -730.939 -1120.84 -445.856
11 2954 -680.548 -1047.33 -397.747
12 2978 -637.332 -1058.83 -415.183
13 2948 -596.095 -1030.59 -334.412
14 2949 -553.915 -963.067 -325.762
15 3063 -520.186 -971.488 -260.163
16 2957 -484.304 -861.326 -260.163
17 3024 -452.281 -955.302 -247.82
18 2939 -419.993 -887.574 -237.846
19 2968 -391.706 -938.699 -212.669
20 3003 -365.013 -837.23 -175.269
21 3013 -338.8 -773.258 -154.681
22 2989 -313.367 -846.464 -138.891
23 3033 -290.654 -735.63 -96.6982
24 3026 -268.264 -787.421 -85.0477
25 3031 -245.839 -739.401 -90.2012
26 2947 -227.527 -774.742 -84.9341
27 3036 -208.849 -725.79 -54.5373
28 2974 -190.253 -687.666 -54.5373
29 3035 -173.176 -669.439 -47.3529
30 3037 -157.32 -664.827 -20.1441
31 3005 -142.523 -685.218 -20.1441
32 3038 -130.647 -672.209 -20.1441
33 3034 -120.205 -669.157 -15.1746
34 2934 -109.288 -747.99 -7.56233
35 2950 -99.6878 -800.502 -1.20275
36 3019 -89.866 -697.724 -0.249842
37 3035 -84.9399 -618.093 0.1574
38 2983 -79.2561 -697.156 0.250377
39 3035 -73.7699 -653.753 0.326752
40 2998 -68.6861 -733.131 0.420127
41 2955 -62.6192 -648.171 0.560875
42 3066 -60.6574 -608.463 0.560875
43 2909 -57.6323 -629.026 0.560875
44 2949 -55.46 -691.81 0.560875
45 3046 -57.5635 -658.029 0.646645
46 3080 -55.558 -678.279 0.724602
47 2955 -58.4815 -717.23 0.724602
48 2985 -55.3568 -674.355 0.724602
49 3093 -54.9966 -713.537 0.75858
50 2933 -57.5 -726.837 0.765629
51 2927 -61.172 -706.837 0.765629
52 3005 -62.4919 -736.047 0.818316
53 2959 -60.5965 -687.391 0.818316
54 2987 -57.9066 -716.047 0.819749
55 3000 -58.2882 -681.17 0.835201
56 2933 -59.4707 -716.929 0.835201
57 3007 -57.7807 -660.257 0.835201
58 3012 -58.8604 -718.704 0.840593
59 2953 -57.6502 -734.808 0.842513
60 3017 -61.3473 -696.42 0.844697
61 2997 -62.5703 -673.568 0.851746
62 3050 -60.4694 -695.629 0.884787
63 2967 -60.0114 -726.935 0.884058
64 3046 -57.294 -730.838 0.884058
65 2995 -59.7632 -731.285 0.884058
66 2968 -60.4451 -696.111 0.884058
67 3006 -59.9833 -724.874 0.884058
68 2999 -57.2582 -651.619 0.884058
69 3043 -58.709 -733.498 0.884058
70 2972 -57.7789 -683.27 0.885206
71 2940 -57.991 -608.739 0.885206
72 2979 -59.1018 -654.209 0.885206
73 2985 -64.2197 -647.472 0.885206
74 2987 -59.8589 -863.475 0.885206
75 2976 -62.3899 -786.916 0.885206
76 2998 -60.6564 -729.62 0.885206
77 3047 -61.3213 -795.346 0.885206
78 2963 -58.8925 -735.821 0.885206
79 2987 -59.5023 -650.488 0.885206
80 2976 -62.3891 -751.52 0.885206
81 3024 -60.2731 -703.15 0.885206
82 3005 -56.9883 -751.113 0.885206
83 3009 -60.2615 -703.578 0.885206
84 3003 -60.0471 -621.138 0.885206
85 3003 -59.6234 -884.891 0.885206
86 3017 -61.21 -670.964 0.885206
87 3047 -59.9479 -728.485 0.885206
88 3019 -63.7722 -697.654 0.885206
89 3041 -62.2421 -771.483 0.885206
90 3051 -60.3648 -717.254 0.885206
91 3002 -61.8827 -752.856 0.885206
92 3020 -60.6895 -614.276 0.885206
93 2979 -61.9008 -665.643 0.885206
94 2941 -57.8349 -725.984 0.885206
95 3003 -61.9024 -740.262 0.885206
96 3057 -61.4431 -669.255 0.885206
97 2980 -63.8181 -645.92 0.885206
98 3000 -64.4953 -725.343 0.885206
99 3002 -61.1017 -769.52 0.885206
100 2956 -61.0198 -682.371 0.885206
Best individual is: [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.10845951732475545, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.09090024122397655, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.013945053542042118, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1658076885870895, 0.0, 0.015302503323372574, 0.0, 0.010987439226133655, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.3663735881178046, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.1089114620959789, 0.0, 0.0, 0.004518749886925355, 0.0]
with fitness: (0.8852062433280787,)
We can see the evolution of our population and as expected with each new generation our max fitness in the population increases until it reaches an approximate optimum point. We also see the best individual and the weights for the portfolio for this date.
Further improvements
As with all our approaches and walkthroughs, this is not the best implementation or even the only way to approach this problem. What this should do is allow you to get started and hopefully, by building on this, create your own evolutionary algorithm approach!
Some of the things you could do to improve your solution:
- Include other constraints in the evaluation function
- Since EAs only provide an approximate solution, we may want to use this as the initial point in more conventional gradient-based optimization approaches | https://blog.quant-quest.com/community/tutorials/using-genetic-algorithms-to-do-portfolio-optimisation/ | CC-MAIN-2021-49 | refinedweb | 2,956 | 68.16 |
Integrate with AdMob to monetize and promote your apps & games with ads on Android and iOS.
Integrate with AdMob to monetize and promote your apps & games with ads on Android and iOS.
Once you have included V-Play AdMob Plugin you can display ad banners and interstitials from Google advertisers in your apps & games. You then get paid every time your users click on ads in your app.
Combine the AdMob Plugin with other plugins like in-app purchases to up-sell users from ad-supported apps to ad-free versions.
The plugin supports all ad types provided by the Google Mobile Ads SDK. In order to use the AdMob plugin, a new AdMob account is required. If you do not have an AdMob account yet, you can create a new one at or connect AdMob with your Google Account.
Always make sure that your usage of AdMob complies to AdMob's Terms of Service. When you place ads in your apps, always think about the user. You do not want to drive your users away by overwhelming them with ads. Therefore, it is important to find the right balance. Google created a detailed guide which is recommended to read before starting off with AdMob.
To monetize your app, you can use Ad Banners, Ad Interstitials and Rewarded Videos. See the sections below for more details of each of them.
You can combine all of these ad types in your app. In fact, it is recommended to use multiple ad types in different placements of your app to optimize your app monetization.
Use Ad banners to display ads within your app without distracting your user from the app's main functionality. You can display ad banners with the AdMobBanner item.
AdMobBanner is the simplest way to show a distraction-free ad. Just add the QML element AdMobBanner where you would like it to show up in your app. There are five different sizes of banners. For more information please see AdMobBanner::banner.
If you just want to include simple banner ads into your apps, Smart Banners are the best fit. They support all device types and sizes and are easy to use. See Example Usage for a simple example. Smart banners automatically choose their size based on the width of the screen.
AdMob also offers a range of different-sized banners. Please note that some of the available sizes can only be used on tablets due to their dimensions.
Banners get only loaded if the QML Item is visible, meaning that it's visible property is not set to
false and all its parent items are visible too.
For more information about ad banners have a look at the AdMobBanner item.
Interstitials are full-screen ads with interactive content that can be presented to the user e.g. when a level of a game was completed or when you your user navigates between two pages. Their key advantage is they do not take away precious screen space while the app is running.
For more information about interstitials have a look at the AdMobInterstitial item.
Rewarded videos are skippable full-screen videos shown to the user. You can reward the user for watching a full video until the end, e.g. with in-game currency or credits. Rewarded videos are used like interstitials: they can be shown at any point in time while the appis running and mostly when navigating between pages.
For more information about rewarded videos have a look at the AdMobRewardedVideo item.
To try the plugin or see an integration example have a look at the V-Play Plugin Demo app.
Please also have a look at our plugin example project on GitHub:.
The AdMobBanner item can be used like any other QML item. Here is a simple example of how to add a SmartBanner at the top of your app with the help of anchoring:
import VPlayApps 1.0 import VPlayPlugins 1 } } } }
To show an interstitial ad you can use the following code snippet, which shows the ad after a call to loadInterstitial():
import VPlayApps 1.0 import VPlayPlugins 1.0 App { NavigationStack { Page { title: "Admob Interstitial" AdMobInterstitial { adUnitId: "ca-app-pub-3940256099942544/1033173712" // interstitial test ad by AdMob testDeviceIds: [ "<your-test-device-id>" ] onInterstitialReceived: { showInterstitialIfLoaded() } onPluginLoaded: { loadInterstitial() } } } } }
The same usage applies for rewarded videos, which can be loaded with loadRewardedVideo():
import VPlayApps 1.0 import VPlayPlugins 1() } } } } }
Here is an example how you can reward the user with virtual currency after he watched a rewarded video ad:
import VPlay 2.0 import VPlayApps 1.0 import VPlayPlugins 1() } } } } } }
With this example code, you can motivate users to watch an ad because they get something for it. Those users who do not want to watch an ad, can also purchase a virtual currency with the above code example. By only showing the ad if the user is below a certain virtual currency threshold, you guarantee users who bought a virtual currency pack do not see the ad. of your app. For example after he finished a game or after he had a success moment like completing a level. You could motivate the user even more to watch an ad by giving extra benefits after such a success moment. This helps you to earn money, while on the other hand giving a benefit to the user - a win-win situation.
Note: If possible, add your devices' device ids to AdMobBanner::testDeviceIds, AdMobInterstitial::testDeviceIds or AdMobRewardedVideo::testDeviceIds during testing your AdMob plugin you need to add the platform-specific native libraries to your project, described here:
GoogleMobileAds.frameworkfrom the
iossubfolder to a sub-folder called
ioswithin your project directory.
.profile:
ios { VPLAY_PLUGINS += admob }
Project-Info.plistfile in the
iossubfolder of your project right before the
</dict></plist>closing tags:
<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsArbitraryLoads</key> <true/> <key>NSAllowsArbitraryLoadsForMedia</key> <true/> <key>NSAllowsArbitraryLoadsInWebContent</key> <true/> </dict>
This ensures that the delivery of ads is not affected by the
App Transport Security feature introduced with iOS 9, as described here.
build.gradlefile and add the following lines to the dependencies block:
dependencies { compile 'net.vplay.plugins:plugin-admob:2.+' }: | https://v-play.net/doc/plugin-admob/ | CC-MAIN-2018-39 | refinedweb | 1,019 | 55.44 |
Hi,@etarena , @ctrueden, @imagejan or whoever understands ImageJ2 Ops and imgLib2:
I have a question about the example for cropping an image using an Op. It seems as if the image is cropped in 3D, but the image in the example seems to be 2D:
This example shows two ops that crop an image:
import net.imglib2.FinalInterval
region = FinalInterval.createMinSize(75, 27, 0, 40, 28, 3)
eye = ij.op().run("crop", image, region)
eyeView = ij.op().run("intervalView", image, region)
tile([eye, eyeView])
When I looked at the Javadocs for createMinSize in the imgLib2 FinalInterval class, I found this:
minsize - a list of 2*n parameters to create a n -dimensional interval.
And since the example given in the notebook was using 6 arguments for createMinSize, I understand that the image was cropped in 3D. Am I right? (it's cool if the image can be cropped that easily in 3D)
Thanks,Avital
Yes, the image was cropped in 3D, because it has actually 3 dimensions: x, y, and Channel.
You can check the number of dimensions:
println image.numDimensions()
and the size of the thirs dimension (index 2):
println image.dimension(2)
Yes, with ops, you can easily crop whatever dimensions your image has. The syntax will remain the same. Awesome, isn't it?
Thanks, Jan - that's super cool! I'm very interested in using it. How would I know which dimension is which? (I mean, how did you know that the channel is the third dimension?)
Right now, you have to use the unstable ImgPlus API, which allows each dimension to have an associated axis. This will change, however, with the "rich image" work on metadata which is a priority for this year.
ImgPlus
Is it possible to threshold my image and segment it in 3D with Ops? If so, how? I think that these tutorials haven't reached beaker yet. If they exist somewhere else, I will be happy to go over them.
Yes, see the thresholding section of the Ops Beaker tutorial.
Not easily yet, unfortunately. There is a CCA (connected component analysis) op, which returns a labeling. You can find a work-in-progress tutorial which illustrates it here.
Thanks, Curtis | http://forum.imagej.net/t/beaker-notebook-3d-crop/4429 | CC-MAIN-2017-26 | refinedweb | 368 | 67.45 |
Speed up your Unit Tests NOW!!!
Many Java developers know they *should* write and run unit tests, but often stop running, or even writing them, for several reasons. One reason I'm both seeing and hearing about more and more lately is the fact that running unit tests takes toooo looooooong. As a result, continuous builds get turned into nightly builds, which means that developers may be committing code that breaks the build without knowing it.
What's a development team to do???? Scale out your build process by setting up a build grid -- it's easier than you think! Ideally this would be transparent (such as having multiple instances of Maven's Surefire plugin running your tests at once, or simply replacing junit.jar), but things aren't quite there yet. However, a solution that requires minimal intervention is fortunately available: Add a single @GridifyTest annotation available in the GridGain API to your JUnit test suites, and that's all you have to do in your codebase.
Nikita Ivanov, the founder of the open source product GridGain,was kind enough to come down to Houston this week to show the Houston JUG just how to do that. He had two grid nodes running on his laptop, and showed how to run the unit tests right from Eclipse with the unit tests running in each of the other nodes. The JUnit bar even came back green, despite the fact that the unit tests weren't being run in Eclipse!!! He did have to add the GridGain jar and its dependent libraries to his project, and set up his JUnit runner to weave his JUnits with GridGain code, but it didn't take much effort. The JVM arguments and code from the Distributed JUnit Overview page are below, with the TestA & TestB classes added.
JVM Arguments:
-javaagent:[GRIDGAIN_HOME]/libs/aspectjweaver-1.5.3.jar
Note: Your Classpath should contain the [GRIDGAIN_HOME]/config/aop/aspectj folder
public class TestA extends TestCase {
public void testA(){
assert(true);
}
}
public class TestB extends TestCase {
public void testB(){
assert(true);
}
}
public class GridifyJunit3ExampleTestSuite {
// Standard JUnit3 suite method. Note we attach @GridifyTest
// annotation to it, so it will be grid-enabled.
@GridifyTest
public static TestSuite suite() {
TestSuite suite = new TestSuite("Example Test Suite");
// Nested test suite to run tests A and B sequentially.
TestSuite nested = new TestSuite("Example Nested Sequential Suite");
nested.addTestSuite(TestA.class);
nested.addTestSuite(TestB.class);
// Add tests A and B.
suite.addTest(nested);
return suite;
}
}
He mentioned that their unit tests were taking an hour to run, and decided to dogfood their own product to see if they could speed up their unit tests. The results were nothing short of staggering: They were able to cut their time down to only 11 minutes, which gets incredibly close to the 10 minutes that is ideal for achieving Continuous Integration. I forget how many grid nodes they used, but it wasn't very many (I think he mentioned it was only 5 or 6), and that they were able to get it working using Team City as their CI server really well.
OK -- you'll need to get GridGain set up and running on at least a few machines to make this possible, but the benefits far outweigh the short amount of time getting the infrastructure in place. Once the grid is in place, you can run the unit tests from any IDE, from your build process, or your CI server since they're all on the same network. You could get very creative about it too -- let's face it -- most of the time desktop CPUs are idle, so why not put them to good use?
You can find the full tutorial about how to distribute your JUnit tests at GridGain's Distributed JUnit Overview page, and instructions on how to install GridGain here. Their Javadocs for their GridifyTest class can be found here.
- Login or register to post comments
- 6554 reads
- Printer-friendly version
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)
Jim Bethancourt replied on Fri, 2008/02/29 - 6:27pm
Nikita Ivanov replied on Fri, 2008/02/29 - 6:40pm
Jim,
It was great to be in Houston and organization was top notch! Great audience and great questions.
Thanks again,
Nikita Ivanov.
Dmitriy Setrakyan replied on Fri, 2008/02/29 - 8:15pm
You can also watch a screencast that shows how to grid-enable your JUnits here:
There are some other interesting screencasts there as well, such as "Grid Application in 15 Minutes" for example.Best,
Dmitriy Setrakyan
GridGain - Grid Computing Made Simple
Thomas replied on Sat, 2008/03/01 - 1:25am
Unit tests should be quick when developing, but thorough in continuous integration (CI).
To do that, you can use a scaling parameter. By default, the test performs only a few iterations (random operation tests, fuzz tests, concurrency tests). This is the quick/shallow setting (the default). When run in CI, the scaling parameter is higher, and more iterations are run. This is the slow/thorough setting.
Another flag is what database to use. When developing, use a quick database in in-memory mode (H2, HSQLDB). In CI, run the tests against the database your customer uses. | http://java.dzone.com/articles/speed-your-unit-tests-now | crawl-002 | refinedweb | 881 | 68.5 |
You will learn how to add your own content types and how you can render them in a template.
In FeinCMS, a content type is something to attach as content to a base model, for example a CMS Page (the base model) may have several rich text components associated to it (those would be RichTextContent content types).
Every content type knows, amongst other things, how to render itself. Think of content types as “snippets” of information to appear on a page.
Simple:
<div id="content"> {% block content %} {% for content in feincms_page.content.main %} {{ content.render }} {% endfor %} {% endblock %} </div> <div id="sidebar"> {% block sidebar %} {% for content in feincms_page.content.sidebar %} {{ content.render }} {% endfor %} {% endblock %} </div>
The minimal content type is an abstract Django model with a render() method, nothing else:
class TextileContent(models.Model): content = models.TextField() class Meta: abstract = True def render(self, **kwargs): return textile(self.content)
All content types’ render() methods must accept **kwargs. This allows easily extending the interface with additional parameters. But more on this later.
FeinCMS offers a method on feincms.models.Base called create_content_type() which will create concrete content types from your abstract content types. Since content types can be used for different CMS base models such as pages and blog entries (implementing a rich text or an image content once and using it for both models makes lots of sense) your implementation needs to be abstract. create_content_type() adds a few utility methods and a few model fields to build the concrete type, a foreign key to the base model (f.e. the Page) and several properties indicating where the content block will be positioned in the rendered result.
Note
The examples on this page assume that you use the Page CMS base model. The principles outlined apply for all other CMS base types.
The complete code required to implement and include a custom textile content type is shown here:)
There are three field names you should not use because they are added by create_content_type: These are parent, region and ordering. These fields are used to specify the place where the content will be placed in the output.
The default render method uses the region key to find a render method in your concrete content type and calls it. This allows you to customize the output depending on the region; you might want to show the same content differently in a sidebar and in the main region for example. If no matching method has been found a NotImplementedError is raised.
This render method tries to be a sane default, nothing more. You can simply override it and put your own code there if you do not any differentiation, or if you want to do it differently.
All render methods should accept **kwargs. Some render methods might need the request, for example to determine the correct Google Maps API key depending on the current domain. The two template tags feincms_render_region and feincms_render_content pass the current rendering context as a keyword argument too.
The example above could be rewritten like this:
{% load feincms_tags %} <div id="content"> {% block content %} {% for content in feincms_page.content.main %} {% feincms_render_content content request %} {% endfor %} {% endblock %} </div> <div id="sidebar"> {% block sidebar %} {% for content in feincms_page.content.sidebar %} {% feincms_render_content content request %} {% endfor %} {% endblock %} </div>
Or even like this:
{% load feincms_tags %} <div id="content"> {% block content %} {% feincms_render_region feincms_page "main" request %} {% endblock %} </div> <div id="sidebar"> {% block sidebar %} {% feincms_render_region feincms_page "sidebar" request %} {% endblock %} </div>
This does exactly the same, but you do not have to loop over the page content blocks yourself. You need to add the request context processor to your list of context processors for this example to work.
Some content types require extra CSS or javascript to work correctly. The content types have a way of individually specifying which CSS and JS files they need. The mechanism in use is almost the same as the one used in form and form widget media.
Include the following code in the <head> section of your template to include all JS and CSS media file definitions:
{{ feincms_page.content.media }}
The individual content types should use a media property do define the media files they need:
from django import forms from django.db import models from django.template.loader import render_to_string class MediaUsingContentType(models.Model): album = models.ForeignKey('gallery.Album') class Meta: abstract = True @property def media(self): return forms.Media( css={'all': ('gallery/gallery.css',),}, js=('gallery/gallery.js',), ) def render(self, **kwargs): return render_to_string('content/gallery/album.html', { 'content': self, })
Please note that you can’t define a Media inner class (yet). You have to provide the media property yourself. As with form and widget media definitions, either STATIC_URL or MEDIA_URL (in this order) will be prepended to the media file path if it is not an absolute path already.
Alternatively, you can use the media_property function from django.forms to implement the functionality, which then also supports inheritance of media files:
from django.forms.widgets import media_property class MediaUsingContentType(models.Model): class Media: js = ('whizbang.js',) MediaUsingContentType.media = media_property(MediaUsingContentType)
Since FeinCMS 1.3, content types are not only able to render themselves, they can offer two more entry points which are called before and after the response is rendered. These two entry points are called process() and finalize().
process() is called before rendering the template starts. The method always gets the current request as first argument, but should accept **kwargs for later extensions of the interface. This method can short-circuit the request-response-cycle simply by returning any response object. If the return value is a HttpResponse, the standard FeinCMS view function does not do any further processing and returns the response right away.
As a special case, if a process() method returns True (for successful processing), Http404 exceptions raised by any other content type on the current page are ignored. This is especially helpful if you have several ApplicationContent content types on a single page.
finalize() is called after the response has been rendered. It receives the current request and response objects. This function is normally used to set response headers inside a content type or do some other post-processing. If this function has any return value, the FeinCMS view will return this value instead of the rendered response.
Here’s an example form-handling content which uses all of these facilities:
class FormContent(models.Model): class Meta: abstract = True def process(self, request, **kwargs): if request.method == 'POST': form = FormClass(request.POST) if form.is_valid(): # Do something with form.cleaned_data ... return HttpResponseRedirect('?thanks=1') else: form = FormClass() self.rendered_output = render_to_string('content/form.html', { 'form': form, 'thanks': request.GET.get('thanks'), }) def render(self, **kwargs): return getattr(self, 'rendered_output', u'') def finalize(self, request, response): # Always disable caches if this content type is used somewhere response['Cache-Control'] = 'no-cache, must-revalidate'
Note
Please note that the render method should not raise an exception if process has not been called beforehand.
Warning
The FeinCMS page module views guarantee that process is called beforehand, other modules may not do so. feincms.module.blog for instance does not.
Used to let the administrator freely integrate 3rd party applications into the CMS. Described in Integrating 3rd party apps.
Comment list and form using django.contrib.comments.
Simple contact form. Also serves as an example how forms might be used inside content types.
Simple content types holding just a file. You should probably use the MediaFileContent though.
Simple content types holding just an image with a position. You should probably use the MediaFileContent though.
Additional arguments for create_content_type():
Mini-framework for arbitrary file types with customizable rendering methods per-filetype. Add ‘feincms.module.medialibrary’ to INSTALLED_APPS.
Additional arguments for create_content_type():
TYPE_CHOICES: (mandatory)
A list of tuples for the type choice radio input fields.
This field allows the website administrator to select a suitable presentation for a particular media file. For example, images could be shown as thumbnail with a lightbox or offered as downloads. The types should be specified as follows for this use case:
..., TYPE_CHOICES=(('lightbox', _('lightbox')), ('download', _('as download'))),
The MediaFileContent tries loading the following templates in order for a particular image media file with type download:
The media file type is stored directly on MediaFile.
The file type can also be used to select templates which can be used to further customize the presentation of mediafiles, f.e. content/mediafile/swf.html to automatically generate the necessary <object> and <embed> tags for flash movies.
Raw HTML code, f.e. for flash movies or javascript code.
Rich text editor widget, stripped down to the essentials; no media support, only a few styles activated. The necessary javascript files are not included, you need to put them in the right place on your own.
By default, RichTextContent expects a TinyMCE activation script at <MEDIA_URL>js/tiny_mce/tiny_mce.js. This can be customized by overriding FEINCMS_RICHTEXT_INIT_TEMPLATE and FEINCMS_RICHTEXT_INIT_CONTEXT in your settings.py file.
If you only want to provide a different path to the TinyMCE javascript file, you can do this as follows:
FEINCMS_RICHTEXT_INIT_CONTEXT = { 'TINYMCE_JS_URL': '/your_custom_path/tiny_mce.js', }
If you pass cleanse=True to the create_content_type invocation for your RichTextContent types, the HTML code will be cleansed right before saving to the database everytime the content is modified.
Additional arguments for create_content_type():
cleanse:
Whether the HTML code should be cleansed of all tags and attributes which are not explicitly whitelisted. The default is False.
A feed reader widget. This also serves as an example how to build a content type that needs additional processing, in this case from a cron job. If an RSS feed has been added to the CMS, manage.py update_rsscontent should be run periodically (either through a cron job or through other means) to keep the shown content up to date. The feedparser module is required.
Combined rich text editor, title and media file.
The default configuration of the rich text editor does not include table controls. Because of this, you can use this content type to provide HTML table editing support. The data is stored in JSON format, additional formatters can be easily written which produce the definitive HTML representation of the table.
This is a content type that just includes a snippet from a template. This content type scans all template directories for templates below content/template/ and allows the user to select one of these templates which are then rendered using the Django template language.
Note that some file extensions are automatically filtered so they won’t appear in the list, namely anything that matches *.~ and *.tmp will be ignored.
Also note that a template content is not sandboxed or specially rendered. Whatever a django template can do a TemplateContent snippet can do too, so be careful whom you grant write permissions.
Imagine that you have developed a content type which really only makes sense in the sidebar, not in the main content area. It is very simple to restrict a content type to a subset of regions, the only thing you have to do is pass a tuple of region keys to the create_content_type method:
Page.create_content_type(SomeSidebarContent, regions=('sidebar',))
Note that the restriction only influences the content types shown in the “Add new item”-dropdown in the item editor. The user may still choose to add the SomeSidebarContent to the sidebar, for example, and then proceed to move the content item into the main region.
Because the admin interface is already filled with information, it is sometimes easier to keep the details for certain models outside the CMS content types. Complicated models do not need to be edited directly in the CMS item editor, you can instead use the standard Django administration interface for them, and integrate them into FeinCMS by utilizing foreign keys. Already the bundled FileContent and ImageContent models can be viewed as bad style in this respect, because if you want to use a image or file more than once you need to upload it for every single use instead of being able to reuse the uploaded file. The media library module and MediaFileContent resolve at least this issue nicely by allowing the website administrator to attach metadata to a file and include it in a page by simply selecting the previously uploaded media file.
So you’d like to check whether Django is properly configured for your content type, or maybe add model/form fields depending on arguments passed at content type creation time? This is very easy to achieve. The only thing you need to do is adding a classmethod named initialize_type() to your content type, and pass additional keyword arguments to create_content_type().
If you want to see an example of these two uses, have a look at the MediaFileContent.
It is generally recommended to use this hook to configure content types compared to putting the configuration into the site-wide settings file. This is because you might want to configure the content type differently depending on the CMS base model that it is used with.
The concrete content type models are stored in the same module as the CMS base class, but they do not have a name using which you could import them. Accessing internal attributes is hacky, so what is the best way to get a hold onto the concrete content type?
There are two recommended ways. The example use a RawContent content type and the Page CMS base class.
You could take advantage of the fact that create_content_type returns the created model:
from feincms.module.page.models import Page from feincms.content.raw.models import RawContent PageRawContent = Page.create_content_type(RawContent)
Or you could use content_type_for():
from feincms.content.raw.models import RawContent PageRawContent = Page.content_type_for(RawContent) | http://www.feinheit.ch/media/labs/feincms/contenttypes.html | CC-MAIN-2015-40 | refinedweb | 2,272 | 55.95 |
To
list() constructor. As dictionaries preserve the order of the keys, the list ordering is preserved.)!
Do Python Dictionaries Preserve the Ordering of the Keys?
Surprisingly, the dictionary keys in Python preserve the order of the elements. So, yes, the order of the elements is preserved. (source)
Countless online resources like this another example:.
Source Article: How to Remove Duplicates From a Python List?
Removing Duplicates From Ordered Lists For Older Versions:
from collections import OrderedDict lst = [1, 1, 9, 1, 9, 6, 9, 7] result = list(OrderedDict.fromkeys(lst))
The output is the following duplicate-free list with the order of the elements preserved:
print(result) # [1, 9, 6, 7]
Interactive Code Shell
Let’s try this method in our interactive Python shell:
Exercise: Run the code. Does it work?
You can find more ways to remove duplicates while preserving the order in this detailed blog article:
Related tutorial: Python List: Remove Duplicates and Keep the. | https://blog.finxter.com/how-to-remove-duplicates-from-a-python-list-while-preserving-order/ | CC-MAIN-2021-43 | refinedweb | 157 | 57.57 |
Quickstart: Adding a FlipView (HTML)
Many apps display a list of items that the user can flip through. These lists might obtain their data from a database, the web, or a JSON data source. Windows Library for JavaScript provides the FlipView control for just this purpose.
Prerequisites
What is a FlipView?
The FlipView is a WinJS control that lets you flip through a collection of items, one at a time. It's great for displaying a gallery of images.
The FlipView gets its data from an IListDataSource. WinJS provides several types of IListDataSource objects:
- You can use a List to create an IListDataSource from an array of data.
- You can use a StorageDataSource to access information about files and directories.
You can also create your own custom data source that connects to some other type of data provider, such as a web service or database. For instructions, see How to create a custom data source.
Creating a simple FlipView
Add references to the WinJS to your HTML file, if they aren't already there.
This example shows the HTML for the default.html file that is generated when you create a new Blank Application project in Microsoft Visual Studio. Note that it already contains references to the WinJS.
<!-- default.html --> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>FlipViewExample</title> <!-- WinJS references --> <link href="//Microsoft.WinJS.2.0/css/ui-dark> </head> <body> <p>Content goes here</p> </body> </html>
This example uses the light style sheet instead of the dark style sheet, so if you want your app to match these examples, change this reference:
...to this:
- In your HTML file, create a div element and set its data-win-control property to "WinJS.UI.FlipView".
In the JavaScript code that accompanies your HTML file, call the WinJS.UI.processAll function when your HTML is loaded.
The next example shows the default.js file that accompanies the default.html file created for you when you create a new Blank Application project.
// default.js (function () { "use strict"; var app = WinJS.Application; // This function responds to all application activations. app.onactivated = function (eventObject) { if (eventObject.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) { // TODO: Initialize your application here. WinJS.UI.processAll(); } }; app.start(); })();
This example works if you're adding the FlipView to your start page (default.html). If you're adding the FlipView to a Page control, you don't need to call WinJS.UI.processAll because the Page control does it for you. If you're adding the FlipView to your own custom HTML, you can use the DOMContentLoaded event to call WinJS.UI.processAll. For more information about activating your controls, see Quickstart: Adding WinJS controls and styles.
- Important: Set the height and width of your FlipView. For a FlipView to render, you must specify its height with an absolute value. Add this CSS to the CSS style sheet for the HTML page that contains the FlipView:
This code creates an empty FlipView. If you run the app, you'll see an empty control. In the next section, you create some data for the FlipView to display.
Defining your data
Putting the code to create your data source in a separate JavaScript file can make it easier to maintain. In this section, you learn how to create a JavaScript file for your data, how to create a List, and how to use the WinJS.Namespace.define function to make the data accessible to the rest of your app.
- Use Visual Studio to add a data file to your project. In the Solution Explorer, right click your project's
jsfolder and select Add > New Item. The Add New Item dialog appears.
- Select JavaScript File. Give it the name "dataExample.js". Click Add to create the file. Visual Studio creates a blank JavaScript file named dataExample.js.
- Open dataExample.js. Create an anonymous function and turn on strict mode.
As described in Coding basic apps, it's a good idea to encapsulate your JavaScript code by wrapping it in an anonymous function, and it's a good idea to use strict mode.
- Create an array of data. This example creates an array of objects. Each object has three properties: type, title, and image.
" } ]; })();Note If you're following along with your code, you can change the pictures to files on your local machine, or you can get the pictures by downloading the HTML FlipView control sample (it's not the same sample, but it uses the same images). You can also run the sample without adding the images—it will still run.
- Use the array to create a List object.
); })();
- Expose the List by declaring a namespace and adding the List as a public member.
Because the code you just wrote in enclosed in an anonymous function, non of it is publicly accessible. (That's part of the reason why you use the anonymous function: to keep private data private.) For your FlipView to be able to access the List, you need to make it publicly accessible. One way to do this is to use the WinJS.Namespace.define function to create a namespace and add the List as one of its members.
The WinJS.Namespace.define function takes two parameters: the name of the namespace to create, and an object that contains one or more property/value pairs. Each property is the public name of the member, and each value is underlying variable, property, or function in your private code that you want to expose.
This example creates a namespace named DataExample that exposes a public member named itemList that returns your List.
); // Create a namespace to make the data publicly // accessible. var publicMembers = { itemList: dataList }; WinJS.Namespace.define("DataExample", publicMembers); })();
You've created a data source that can be accessed by your FlipView. In the next section, you connect the data to the FlipView.
Connecting your data to the FlipView
- In the head section of the HTML file that contains your FlipView, add a reference to the data file you just created (dataExample.js):
<head> <meta charset="utf-8"> <title>FlipViewExample</title> <!-- WinJS references --> <link href="//Microsoft.WinJS.2.0/css/ui-light> <!-- Your data file. --> <script src="/js/dataExample.js"></script> </head>
- Use the data you created in the last section to set the FlipView control's itemDataSource property.
The itemDataSource property takes an IListDataSource object. The List object is not an IListDataSource, but it does have a dataSource property that returns an IListDataSource version of itself.
To connect your data, set the FlipView control's itemDataSource property to
DataExample.itemDataList.dataSource:
Run the app. The FlipView displays the properties and values in the data source:
This isn't quite the look that we want. We want to show just the values of the title field, and we want to show the actual images, not the path to the images. To get the rendering that we want, we need to define a Template. The next step shows you how.
Defining an item template
At this point, the FlipView has the data it needs, but doesn't know how to display it. For that, you need an item template. There are two ways to create a template: you can use markup to define a WinJS.Binding.Template, or you can create a templating function. This example creates a template in markup. (For information about creating a template function, see the itemTemplate property.)
A WinJS.Binding.Template is easy to create: you define the markup that you want to use to display each list item, then you indicate where each data field is displayed.
In your HTML, create a WinJS.Binding.Template control and assign it an ID. This example uses the ID "ItemTemplate".Note Your template must be defined before you use it, so add the HTML for our template before the HTML for your FlipView.
- WinJS.Binding.Template must have a single root element. Create a div element to serve as a parent for the template's contents.
Create the markup that the FlipView will produce for each data item it contains. The data you created in the previous section contains an image location, a title, and some text, so create these elements:
(This example also adds an extra div element for formatting reasons.)
Set the data-win-bind attribute on each element that displays data. The data-win-bind attribute uses the syntax:
For example, to bind the src property of an img to the "picture" field, use the syntax:
To set multiple properties, you separate them with a semicolon:
This example binds the items in the template to their corresponding data fields.
To use the item template, set the itemTemplate property of the FlipView to the ID of your item template ("ItemTemplate" in this example).
<div id="ItemTemplate" data- <div> <img src="#" data- <div> <h2 data-</h2> </div> </div> </div> <div id="basicFlipView" data-</div>
Now when you run the app, the bound data appears in the list.
Note that there are some formatting issues: the title text doesn't display. The next section shows you how to fix the issue by styling the template.
Styling items
You can use CSS to style your item template. The next example adds some CSS classes to the template you defined in the Defining an item template section.
<div id="ItemTemplate" data- <div class="overlaidItemTemplate"> <img class="image" src="#" data- <div class="overlay"> <h2 class="ItemTitle" data-</h2> </div> </div> </div> <div id="basicFlipView" data-</div>
In the CSS style sheet for your HTML file, add these styles for the template:
#basicFlipView { width: 480px; height: 270px; border: solid 1px black; } /**********************************************/ /* */ /* Styles used in the item template */ /* */ /**********************************************/ .overlaidItemTemplate { display: -ms-grid; -ms-grid-columns: 1fr; -ms-grid-rows: 1fr; width: 480px; height: 270px; } .overlaidItemTemplate img { width: 100%; height: 100%; } .overlaidItemTemplate .overlay { position: relative; -ms-grid-row-align: end; background-color: rgba(0,0,0,0.65); height: 40px; padding: 20px 15px; overflow: hidden; } .overlaidItemTemplate .overlay .ItemTitle { color: rgba(255, 255, 255, 0.8); }
Here's what the FlipView looks like now:
Changing the font-family for FlipView navigation buttons will cause buttons to no longer contain the correct glyph.
Changing the orientation of the FlipView
By default, the FlipView uses a horizontal orientation. You can display the FlipView vertically by setting its orientation property to "vertical".
Adding interactive elements to an item template
The item template can contain most other controls, but it can't contain a ListView or another FlipView.
Normally, when the user interacts with an element, the FlipView captures that interaction and uses it to determine whether the user selected or invoked an item or is panning through items. For an interactive element, such as a control, to receive input, you must attach the
win-interactive class to the interactive element or one of its parent elements. That element and its children receive the interaction and no longer trigger events for the FlipView.
When you attach the
win-interactive to an element in a item template, be sure that the element doesn't fill the entire item, otherwise the user won't have a way to select or invoke that item.
To add interactive elements to your item template, you must use a templating function instead of a WinJS.Binding.Template. For an example of how to do this, see the HTML FlipView control sample. For more info about templating functions, see the examples in the FlipView.itemTemplate.
Creating a context control
The FlipView exposes methods and events that allow you to create custom controls that give the user an idea of where current item is and alternative mechanisms for navigating the collection. The following image shows a set of styled radio buttons that are kept in sync with the FlipView via the pageselected and pagevisibilitychanged events.
For the code that shows you how to do this, see the HTML FlipView control sample.
Related topics | https://msdn.microsoft.com/en-us/library/windows/apps/Hh465425(v=win.10)?cs-save-lang=1&cs-lang=cpp | CC-MAIN-2016-36 | refinedweb | 1,979 | 65.01 |
I have a field named "arrondissement" (district), which contains as attributes integers from 1 to 20. My task is to create a column for each arrondissement with the ranks (short integers) relative to the shape area for the connecting areas to voting stations of the same district.
I hope it makes sense, not really sure how to do it to be honest I'm lost at the moment. Besides adding a field, perhaps multiple ones with a loop by using ListFields and AddField, I don't really know what else to do.
EDIT:
While figuring out what I have to do, practically creating a field for each arrondise, and in each, rank each FID (which are part of the respective arrondise) by the size of its shape area.
import arcpy arcpy.env.workspace = "D:/M1 Geomatique/Programmation II/Dossier" fc = "zones_rattachement.shp" try: fieldRoot = "RANG_R" for counter in range(1,21): arcpy.AddField_management(fc, fieldRoot + str(counter),'SHORT') size_rank = 1 numlist = list(range(1,21)) for num in numlist: arcpy.SelectLayerByAttribute_management(fc, "NEW_SELECTION", "arrondisse = '%c'") rows = arcpy.UpdateCursor(fc, sort_fields="shape_area D") for row in rows: row.setValue("RANG_R1", size_rank) size_rank += 1 rows.updateRow(row) except: arcpy.GetMessages()
Message was edited by: Florin-Daniel Cioloboc
Message was edited by: Florin-Daniel Cioloboc
Then you will need to add .shp to the end of your feature class name.
Also, your field name is too long, they need to be 10 or fewer. Since you are going to be tacking on up to two characters to the end, you will need to have a field name 8 characters or fewer. | https://community.esri.com/thread/154230-creating-multiple-fields-with-ranks-using-arcpy | CC-MAIN-2018-43 | refinedweb | 268 | 65.62 |
Hello Alex,
Am Sonntag, 3. November 2002 22:01 schrieb Alex Moffat:
> I maintain XSLTXT which is a compact form for encoding xslt stylesheets
> (). I want to extend the ant "style"
I have taken a look at the site you cited.
choose
when .test "$count > 1"
call "by-columns" ("column-count":"$count")
otherwise
<para>
"No columns"
Basically, the idea is great.
I see fewer sources for typos and not-wellformedness.
But: How das XSLTXT detect the end of the para, the otherwise and the choose
section? By indention? Geee! People already hate make!
I'd rather like to write:
if ($count > 1) {
call by-columns(column-count=$count);
} else {
<para> {
"No columns";
}
}
or:
if ($count > 1)
call by-columns(column-count=$count);
else
<para>"No columns";
Use {} for blocks and indention doesn't matter.
Using ; as simple statement delimiters allows to even omit {} if a block
contains only one statement. This shortens further.
"" would not have been neccessary, for what distinction? From Vars? They are
preceeded with $count already.
So use "" only for strings as such, like "'blabla'" and <xsl:text/> in XSLT or
for literal result text nodes.
whenever if has an else, choose when otherwise is used instead of if.
test is always used for when or if, so it is superflous.
Colon for parameters? Usually always = is used for assignment, and : is
associated with namespaces.
Anyway I can't use XSLTXT because I already use XSLT 2.0 (saxon 7.2).
But the idea is great.
Bye
--
ITCQIS GmbH
Christian Wolfgang Hujer
Geschäftsführender Gesellschafter
Telefon: +49 (0)89 27 37 04 37
Telefax: +49 (0)89 27 37 04 39
WWW:
--
To unsubscribe, e-mail: <mailto:ant-dev-unsubscribe@jakarta.apache.org>
For additional commands, e-mail: <mailto:ant-dev-help@jakarta.apache.org> | http://mail-archives.apache.org/mod_mbox/ant-dev/200211.mbox/%3C200211032249.46580.Christian.Hujer@itcqis.com%3E | CC-MAIN-2015-22 | refinedweb | 297 | 67.86 |
20 September 2012 14:51 [Source: ICIS news]
HOUSTON (ICIS)--ExxonMobil has struck a deal to increase its production acreage in the Bakken oil shale region in ?xml:namespace>
Under the deal, ExxonMobil and its subsidiary XTO Energy agreed to acquire Denbury Resource's Bakken shale assets.
The acquired assets consist of about 196,000 acres, with expected production in the second half of 2012 of more than 15,000 oil equivalent barrels per day, ExxonMobil said.
The agreement increases ExxonMobil’s holdings in the Bakken by about 50% to nearly 600,000 acres, giving the company a significant presence in one of the major
In exchange, Denbury will receive $1.6bn (€1.2bn) in cash, and it will acquire ExxonMobil’s interests in the Hartzog Draw field in Wyoming and the Webster field in Texas, which produce about 3,600 net oil equivalent bbl/day of natural gas and liquids (NGLs), ExxonMobil said.
In a separate statement, Denbury said that the two fields are ideal candidates for carbon dioxide (CO2) flooding, which is a process to improve oil recovery from reserves.
Denbury added that it also agreed in principle to either purchase an interest in the CO2 reserves in ExxonMobil's LaBarge Field in southwestern
( | http://www.icis.com/Articles/2012/09/20/9597371/exxonmobil-to-increase-production-in-us-bakken-shale-oil-region.html | CC-MAIN-2014-52 | refinedweb | 206 | 52.12 |
Question
If I am selling goods to a French company and they are paying me from France (by BACS) and they then want to collect from our UK premises, is it OK that we are not charging VAT?
Answer
Hello Lindy
My name is Chris Willers and I run an export services company called Access to Export Ltd based near Cambridge. In order to zero rate the goods for VAT your French customer must provide you with their French VAT number which should be shown on your invoice to them. If you do not have their VAT number you are obliged to charge UK VAT on your invoice. I would also suggest you get "proof of export" such as a Certificate of Shipment from the company that collects the goods from you. Also you will need to include the sale in your VAT return (box 8) and EC sales list and also on your Intrastat return if required.
I hope this helps but if you would like me to help further please feel free to contact directly either by e-mail chris@accesstoexport.com or by phone 01223 890767.
Kind regards
Chris
Answer
hi I would have provided a similar answer to Christopher, you first need to check if the company is VAT registered if you want to 0-rate your invoice. you can check a VAT registration number from any EU countries on the VIES system: from the European Commission.
I hope this helps.
Mathilde | https://opentoexport.com/questions/export-to-a-french-company/ | CC-MAIN-2018-05 | refinedweb | 246 | 74.53 |
Hello
I have several datapoints in space. I’m binning and taking the average and I’m trying to plot these in different ways: contourf, streamplot and quiver. But before plotting I am making and interpolation with LinearTriInterpolator.
However some bins are empty and with the interpolation these bins will magically have data and will be plotted. To make this distinction I thought of using alpha=1 for occupied bins and something else for vacant bins.
I managed to do this with scatterplots as follows:
import numpy as np from matplotlib import cm from matplotlib.colors import Normalize import matplotlib.pyplot as plt color_array = np.array([1,2,3,4,5]) alpha_array = np.array([2,10,0,0,2], dtype=np.float32) alpha_array[alpha_array != 0] = 1 alpha_array[np.isclose(alpha_array,0)] = 0.3 norm = Normalize(vmin=color_array.min(), vmax=color_array.max()) cmap = cm.get_cmap('viridis') color_array = norm(color_array) color_array = cmap(color_array) color_array[...,-1] = alpha_array plt.scatter([1,2,3,4,5], [1,2,3,4,5], c=color_array)
In this toy example I have 5 bins and alpha_array contains the occupation number of each bin and because of the normalization, the alphas will be [0.2, 1. , 0. , 0. , 0.2]
This works very nicely with scatterplots since I can pass “A 2D array in which the rows are RGB or RGBA.” but for the contourf, quiver and streamplot I can’t find this option. (and if I try to force it using the colors arguments on contourf for example, it complains because it’s not expecting RGB or RGBA)
Am I missing something? Is it possible to do it?
I am using ubuntu 20.04 LTS and matplotlib 3.4.1 on python 3.8
Thanks in advance
Pedro | https://discourse.matplotlib.org/t/complex-plots-with-varying-alpha-values/22053 | CC-MAIN-2021-21 | refinedweb | 290 | 61.02 |
Just a quick reply because I am just coming from the beach and have to
tranquilize my sunburn ASAP. ;-)
All questions already answered by Ross I will not answer. ;-)
On Sun, 2005-05-01 at 22:51 -0700, Diwaker Gupta wrote:
> Hi.
>
:)
It is mainly produced in the contracts which resides in
{viewHelper}/templates.
>?
>
I will fix that after the sunburn. ;-)
> :)
>
That is an old problem that we need to fix as well in views.
> o The feedback contract generates a div tag with an attribute
> xmlns:jx, which is again invalid. Why is this needed?
>
This is from an old experiment of mine.
...anyway namespaces *are allowed* in xhtml.
> Finally, validation will go a lot smoother if we just use XHTML
> transitional instead of XHTML strict for now. Once we validate
> transitional, we can push for strict. Though I'm all for aiming for
> strict from the beginning!
>
:) I will help you with the patch and if you want to start with
transitional that is fine with me (we just have to try going for strict
before 0.8 gets out).
> cheers,
> Diwaker
Thanks for your work.
salu2
--
thorsten
"Together we stand, divided we fall!"
Hey you (Pink Floyd) | http://mail-archives.apache.org/mod_mbox/forrest-dev/200505.mbox/%3C1115048297.4570.32.camel@localhost.localdomain%3E | CC-MAIN-2015-40 | refinedweb | 200 | 85.99 |
Easy-Peasy Peripheral Interfacing with Pi, Python and Pmods!
The perfect combination for cooking up peripheral interfacing recipes in no time at all.
The Pmod — peripheral module — is an open specification standard by Digilent that is designed for interfacing peripherals with FPGA and microcontroller host platforms. Available in 6-pin and 12-pin versions, with a characteristically compact form factor, they provide a neat solution to system prototyping and with many engineers owning at least a small selection of Pmods.
Just as the diverse array of available Pmods makes it possible to quickly prototype a wealth of hardware configurations, the eminently approachable Python programming language and its bountiful software ecosystem make it possible to rapidly prototype applications.
Throw a Raspberry Pi into the mix also and you’ve got a powerful prototyping platform. However, there are a couple of things, on the hardware and software side, which would make integration and rapid prototyping just that bit easier. So let’s start with the former and enter the Pmod HAT!
DesignSpark Pmod HAT
The Pmod HAT (144-8419) has three 2x6-pin Pmod ports with support for I2C, SPI, UART and GPIO interfacing. It can be used with any model of Raspberry Pi that has a 40-pin GPIO connector, with power being supplied via either this or a barrel connector and external 5VDC power supply.
The ports are labelled as follows:
- JA: supports SPI and GPIO Pmods.
- JB: supports SPI and GPIO Pmods, plus 6-pin I2C Pmods on the bottom row.
- JC: supports UART and GPIO Pmods.
There are also two jumpers:
- JP1 & JP2: Enables pull-up resistors on JB2 I2C when shorted.
- JP3: Enables writing to the onboard EEPROM.
The EEPROM stores a device tree fragment which is used to identify the board and configure the O/S and drivers accordingly. For those not familiar with the device tree concept, it is a compiled database that is used to describe an ARM-based system and provides functionality similar to the BIOS of an Intel/AMD computer. This would only be modified with more advanced use cases.
So, now we have a convenient way of plumbing together the hardware that avoids having to use messy jumper wires, what about the software? Enter DesignSpark.Pmod!
DesignSpark.Pmod
DesignSpark.Pmod is a Python library that:
- Provides simple, consistent interfaces for supported Pmods
- Checks that Pmod and port capabilities match
- Checks for port usage conflicts
- Is provided with examples to get you started
Pin multiplexing is standard with many (most?) modern SoCs and it can bring great flexibility but at the expense of having to do some initial setup to configure I/O pins for your particular use. While Pmods can be interfaced via one of a number of different methods and when you combine these two things together, it does mean that you do need to take care to not e.g. connect SPI and GPIO Pmods to ports which share host I/O pins and which would, therefore, result in a setup conflict.
What the library does is to check that a Pmod is supported by a particular port on the HAT and that this use would not be in conflict. The initial release also provides convenient interfaces for 6x Pmods and the library has been written in such a way that it can be extended to support more.
Installation
First we need to make sure that SPI is enabled and this can be done using raspi-config.
$ sudo raspi-config
Selecting:
- Option 5 - Interfacing
- P4 - SPI
- Enable → YES
Next, we need to install a few Raspbian build dependencies:
$ sudo apt-get update $ sudo apt-get install python-pip python-dev libfreetype6-dev libjpeg-dev build-essential
Finally, we can use the Python package manager to install DesignSpark.Pmod and dependencies:
$ sudo -H pip install designspark.pmod
Note that the official docs can be found at:
This website should always be referred to for the latest documentation.
The associated PyPi project page and GitHub development repository are located at:
Interfacing with Pmods
At the time of writing six Pmods are supported by the library and next, we’ll take a quick look at these and basic methods for interfacing with them.
PmodAD1
PmodAD1 (134-6443) is a two channel 12-bit ADC that features Analog Devices’ AD7476A, with a sampling rate of up to 1 million samples per second, and a 6-pin SPI Pmod interface.
To read from this we simply need to import the library, create an object with the AD1 module on a suitable port, then use the readA1Volts() method to get an ADC reading. E.g.:
from DesignSpark.Pmod.HAT import createPmod adc = createPmod('AD1','JBA') volts = adc.readA1Volts() print(volts)
In this example using port “JAA”, which is the top row of the 2x6 pin JA connector.
Note that at the present time only ADC channel A1 is supported due to the way that SPI is configured when used with a Pi.
PmodHB3
The PmodHB3 (Digilent part no.410-069) is a 2A H-bridge circuit for DC motor drive up to 12V, with a 6-pin GPIO interface.
Once again we import the library and then to spin the motor in the forward direction simply:
motor = createPmod('HB3','JAA') motor.forward(20)
The number passed to the forward method is the duty cycle. There are also methods to spin in the reverse direction, stop, change the PWM frequency and clean up.
PmodISNS20
Like the AD1, the Pmod ISNS20 (136-8069) is another 6-pin SPI Pmod, but this time a ±20A DC or AC input, high accuracy current sensor. After importing the library, to read from this we would:
isens = createPmod('ISNS20','JBA') mA = isens.readMilliAmps() print(mA)
Simple.
MIC3
By now you should be used to this and to read an integer value from the PmodMIC3 (Digilent part no.410-312) ADC we would import the library, following which:
mic = createPmod('MIC3','JBA') int = mic.readIntegerValue() print(int)
OLEDrgb
The PmodOLEDrgb (134-6481) is an organic RGB LED module with a 96×64 pixel display and that is capable of 16-bit colour resolution. It is the first 12-pin Pmod we will have encountered. It is also the first which will require a couple of additional libraries for use.
To draw “Hello, World!” in a bounding box we would simply:
from DesignSpark.Pmod.HAT import createPmod from luma.core.render import canvas from luma.oled.device import ssd1331 oled = createPmod('OLEDrgb','JA') device = oled.getDevice() with canvas(device) as draw: draw.rectangle(device.bounding_box, outline="white", fill="black") draw.text((16,20), "Hello, World!", fill="white") while True: pass
The luma.core and luma.oled libraries provide a lot of really great functionality that can be used with this Pmod and checking out the associated documentation is highly recommended.
TC1
Finally, PmodTC1 (134-6476) is another 6-pin SPI Pmod, this time featuring a cold-junction thermocouple-to-digital converter designed for a classic K-Type thermocouple wire. The wire provided with the module has an impressive temperature range of -73°C to 482°C.
After importing the library to read from this we would:
therm = createPmod('TC1','JBA') cel = therm.readCelcius() print(cel)
Complete basic examples for each of the above Pmods, along with a couple that is slightly more advanced — which includes an analog clock face example for the OLEDrgb module — are provided together with API documentation via Read the Docs.
Wrapping up
So there we have it, thanks to the DesignSpark Pmod HAT and supporting library, we can now interface Pmods and prototype applications using a Raspberry Pi and Python faster than ever before. It should also now be reasonably straightforward to add support for additional Pmods to the library and if you would like to contribute support for a new module get in touch.
December 2, 2017 13:43
Great article! Definitely investing the time to explore soon.... | https://www.rs-online.com/designspark/easy-peasy-peripheral-interfacing-with-pi-python-and-pmods | CC-MAIN-2018-09 | refinedweb | 1,320 | 61.46 |
14 April 2010 15:14 [Source: ICIS news]
LONDON (ICIS news)--The European adipic acid market is at a critical point because of low availability resulting from stronger-than-expected demand in Asia and undercapacity due to previous plant closures, market sources said on Wednesday.
“I don’t remember in my history there being such a shortage. All I can say is the market is terribly short,” said an adipic acid buyer for the production of polyurethane.
The buyer said it believed that the tightness in Europe was the result of a combination of factors, including the closure of Invista’s 270,000 tonne/year facility in the UK, as well as closures in the US, and “the extreme and sharp demand in China” for nylon and non-nylon applications.
“It’s not a matter of price, it’s a matter of getting the product,” said the buyer.
According to a major producer, there were two main reasons for the current state of the European adipic acid market.
“In 2008, people closed down, especially Invista, and there have been no new capacities in ?xml:namespace>
“Demand in Asia is booming,
A second major producer, which also voiced concerns about low availability, expressed the need to narrow the gap between the values of adipic acid in Europe and those in
“The price gap between Europe and Asia is substantial, because the price increase in Asia started earlier,” said the second producer, adding that European suppliers would continue to export to
In Asia this week, spot adipic acid moved up $50/tonne (€37/tonne) to $2,600-2,700/tonne CFR (cost and freight) NE (northeast) Asia, according to data from global chemical market intelligence service ICIS pricing.
In Europe, a producer and a distributor both valued spot adipic acid at €1,800-1,900/tonne FD (free delivered) NWE (northwest
($1 = €0.74)
For more on adipic acid | http://www.icis.com/Articles/2010/04/14/9350850/europe-suffers-adipic-acid-shortage-amid-strong-demand-in.html | CC-MAIN-2013-48 | refinedweb | 317 | 50.09 |
Summary
Returns a list of datasets in the current workspace. Search conditions can be specified for the dataset name and dataset type to limit the list that is returned.
Discussion
The workspace environment must be set before using several of the list functions, including ListDatasets, ListFeatureClasses, ListFiles, ListRasters, ListTables, and ListWorkspaces.
Syntax
ListDatasets ({wild_card}, {feature_type})
Code sample
List feature dataset names that start with C.
import arcpy arcpy.env.workspace = "c:/data" # Print to the Interactive window all the feature datasets in the # workspace that start with the letter C. datasets = arcpy.ListDatasets("C*", "Feature") for dataset in datasets: print(dataset)
List feature dataset names that start with c or f, start with letters except c, or contain both c and f.
import arcpy arcpy.env.workspace = 'c:/data' # Print to the interactive window all the feature datasets in the # workspaces that start with the letter c or f. datasets1 = list(set(arcpy.ListDatasets("c*", "Feature")) | set(arcpy.ListDatasets("f*", "Feature"))) print(datasets1) # workspaces that start with the letters except c datasets2 = list(set(arcpy.ListDatasets("*", "Feature")) - set(arcpy.ListDatasets("c*", "Feature"))) print(datasets2) # workspaces that contain both the letter c and f datasets3 = list(set(arcpy.ListDatasets("*c*", "Feature")) & set(arcpy.ListDatasets("*f*", "Feature"))) print(datasets3) | https://pro.arcgis.com/en/pro-app/latest/arcpy/functions/listdatasets.htm | CC-MAIN-2021-21 | refinedweb | 207 | 59.6 |
CP(1) NetBSD General Commands Manual CP(1)Powered by man-cgi (2020-09-24). Maintained for NetBSD by Kimmo Suominen. Based on man-cgi by Panagiotis Christias.
NAME
cp -- copy files
SYNOPSIS
cp [-R [-H | -L | -P]] [-f | -i] [-alNpv] source_file target_file cp [-R [-H | -L | -P]] [-f | -i] [-alNpv] source_file ... target_directory
DESCRIPTION
In the first synopsis form, the cp utility copies the contents of the Archive mode. Same as -RpP. . -l Create hard links to regular files in a hierarchy instead of copy- ing. -N When used with -p, don't copy file flags. -P No symbolic links are followed. This is the default. -p Causes cp to preserve in the copy as many of the modification time, access time, file flags, file mode, user ID, group ID, and extended attributes, as allowed by permissions. If the user ID and group ID cannot be preserved due to insufficient permissions, no error message is displayed and the exit value is not altered. If the source file has its set user ID bit on and the user ID can- not. Extended attributes from all accessible namespaces are copied; oth- ers are ignored. If an error occurs during this copy, a message is displayed and cp skips the other extended attributes for that file. -R If source_file designates a directory, cp copies the directory and the entire subtree connected at that point. This option also causes symbolic links to be copied, rather than followed, and for cp to create special files rather than copying them as normal files. Created directories have the same mode as the corresponding source directory, unmodified by the process's umask. Note that cp copies hard linked files as separate files. If you need to preserve hard links, consider using a utility like pax(1) instead. -v Causes cp to be verbose, showing files as they are copied. For each destination file that already exists, its contents are overwrit- ten if permissions allow, but its mode, user ID, and group ID are unchanged. ful- filled other and the command's actions are determined by the last one specified. The default is as if the -P option hadOs.
SEE ALSO
mv(1), pax(1), rcp(1), umask(2), fts(3), symlink(7)
STANDARDS
The cp utility is expected to be IEEE Std 1003.2 (``POSIX.2'') compati- ble. The -a and -l flags are non-standard extensions. They are intended to be compatible with the same options which other implementations, namely GNU coreutils and FreeBSD, of this utility have. The -v option is an extension to IEEE Std 1003.2 (``POSIX.2'').
HISTORY
A cp utility appeared in Version 1 AT&T UNIX. NetBSD 9.99 December 22, 2018 NetBSD 9.99 | https://man.netbsd.org/cp.1 | CC-MAIN-2021-10 | refinedweb | 454 | 65.93 |
Hi all,thats the first mail of the thread I read so I can not really reconstruct all the things you have allready discussed.
AA
which files depends on what.Normaly you simple have to add the files you add to the project to the corrosponding .am files. But that is the part Bill is supporting me! Thanks! I have myself no contect to autotools, so I am not the person to help for build systems.... :-)
ATTENTION:In my makefile I inlcude a config.h file which only I need! That is the solution for having a lot off different linux systems with a lot of different install pathes to the utils we need. So simple add by hand your pathes and write the things direct into your Makefile and forget the terrible things arround that. That makefile is MY PERSONAL one, so dont´t ask why I do it this way... :-)
If you need some more hints simply ask here in simulavr-devel list. Thanks Klaus
Hi Bill, Michael, No offense, but can we move the conversation over to the simulavr-devel list where it's more appropriate than avr-libc-dev? I've CCed the simulavr-devel list. Thanks, Eric Weddington-----Original Message----- From: address@hidden [mailto:address@hidden org] On Behalf Of William Rivet Sent: Sunday, September 09, 2007 11:53 AM To: Michael Hennebry Cc: address@hidden Subject: [avr-libc-dev] Re: simulavrxx build problems Ahh...now I remembere. I don't have time to give a proper response, however I can say that you should not look at the Makefile first, you should look at the corresponding Makefile.am as it is the input that leads to the actual Makefiles. src/Makefile.am shoudl be helpful. I'd recommend learning more about the GDB and simulavrpp interface first. i.e. run your own code in simulavrpp and control it throguh GDB. The examples have the basics for that. If you really need to code to get at the rigiht breakpoints, then I see why you are interested in the build...again, the ".am" files are what you need to look at. On Sun, 2007-09-09 at 12:11 -0500, Michael Hennebry wrote:On Sat, 8 Sep 2007, William Rivet wrote:On Sat, 2007-09-08 at 16:20 -0500, Michael Hennebry wrote:One of the problems that I'm having is that for the most part, I can't even read the make files.What is it you are trying to do?I have some multi-ATmega168 boards. They are poorly connected for debugging. Even when the problem manifests on a processor I can connect to, timing issues usually defeat the effort. I would like to be able to simulate interprocessor communication and charlieplexed LEDs. I would like to be able to set "breakpoints" based on criteria complex enough to require code. To do these things, I will need to edit the source. I started to write atmega168.h and atmega168.cpp based on atmega128.h and atmega128.cpp, but it occured to me that even if I accomplished that, I wouldn't know what to do with the result.It would be nice to have overviews of what makes what from what and what runs what.This is true. The root directory includes theconventional INSTALL filethat describes configuring, building and installing. I'mnot saying theyare great, but it can get things started.I did get it built. Bill helped me with that, but I still had to fix things. What I remember offhand: Flags for position-independent code. The directory for python.h The hexadecimal version number for python.In the examples directory there is a readme about theexample targets.It's not much, but that's what exists ATM.I've run dogdb and do_python. I'm not clear on what to do to run my own avr code.I'm reading up on swig, but I've never used it before. Does swig make simulavr.py and simulavr_wrap.cpp? If so, I've been unable to find the Makefile commandthat does it.Is _simulavr.so made from simulavr_wrap.cpp?Yes. Swig makes interfaces between high level languagesand C/C++ code.What is the input to swig? I've not been able to find the swig command in the make files.What is the startup sequence? That is, who invokes whom on the way to the main loop? During the main loop, who sends what information to the outside world? How? Who gets information from the outside world? How?I'm just guessing here though, I'm sorry if I'm off target.As noted above, I'm going to need to add code to the simulator._______________________________________________ AVR-libc-dev mailing list address@hidden Simulavr-devel mailing list address@hidden
#include the global configuration file include ../../config.h # attention: if -DPROF is also defined here the simulation breaks # after 1000000 steps!!!! Dont wonder about that again :-) #PROF=-pg #PROF=-pg -DPROF #PROF= #CXX=/opt/linux/bin/g++ #CC=/opt/linux/bin/gcc #CFLAGS= -g -Wall $(PROF) -O3 -funroll-loops -fstrict-aliasing -fsched-interblock -falign-loops=16 -falign-jumps=16 -falign-functions=16 -falign-jumps-max-skip=15 -falign-loops-max-skip=15 -fomit-frame-pointer -foptimize-sibling-calls -finline-all-stringops -funit-at-a-time -funswitch-loops -ffast-math -march=i686 -mtune=pentium3 -I$(BFD)/bfd CFLAGS= -g -Wall $(PROF) -O2 -mtune=pentium3 -I$(BFD)/bfd -I./../.. #CFLAGS= -g -Wall $(PROF) -O2 -mcpu=pentium3 -I$(BFD)/bfd CXXFLAGS = $(CFLAGS) simulavr_wrapHEADER= serialtx.h serialrx.h avrdevice.h at8515.h atmega128.h at4433.h systemclock.h ui.h hardware.h pin.h net.h trace.h gdb.h lcd.h simulavr: $(OBJECTS) $(CXX) $(CFLAGS) $(OBJECTS) $(BFD)/bfd/libbfd.a $(BFD)/libiberty/libiberty.a -lncurses -lc -lm -o simulavr # pull in dependency info for *existing* .o files -include $(OBJECTS:.o=.d) # compile and generate dependency info; # will also become command-less, prereq-less targets # sed: strip the target (everything before colon) # sed: remove any continuation backslashes # fmt -1: list words one per line # sed: strip leading spaces # sed: add trailing colons %.o: %.c $(CC) -c $(CFLAGS) $*.c -o $*.o $(CC) -MM $(CFLAGS) $*.c > $*.d @mv -f $*.d $*.d.tmp @sed -e 's|.*:|$*.o:|' < $*.d.tmp > $*.d @sed -e 's/.*://' -e 's/\\$$//' < $*.d.tmp | fmt -1 | \ sed -e 's/^ *//' -e 's/$$/:/' >> $*.d @rm -f $*.d.tmp %.o: %.cpp $(CXX) -c $(CXXFLAGS) $*.cpp -o $*.o $(CXX) -MM $(CXXFLAGS) $*.cpp > $*.d @mv -f $*.d $*.d.tmp @sed -e 's|.*:|$*.o:|' < $*.d.tmp > $*.d @sed -e 's/.*://' -e 's/\\$$//' < $*.d.tmp | fmt -1 | \ sed -e 's/^ *//' -e 's/$$/:/' >> $*.d @rm -f $*.d.tmp #special targets for ui-keyboard keytrans.h: keynumber_to_scancode.dat xcode_to_keynumber.dat kbdgentables kbdgentables kbdgentables: kbdgentables.cpp $(CXX) $(CXXFLAGS) kbdgentables.cpp -o kbdgentables keyboard.o: keytrans.h clean: rm -f *.o simulavr simulavr.so *.bin *.srec *.oo *.om *binm *wrap.c *wrap.cxx *.so tags *.o.go *_out dump *.d rm -f keytrans.h kbdgentables rm -f gmon.out rm -f *.gch rm -f *.Plo rm -rf .deps rm -rf .libs simulavr_wrap.cxx: simulavr.i $(TCLHEADER) swig -c++ simulavr.i simulavr_wrap.o: simulavr_wrap.cxx $(CXX) $(CXXFLAGS) simulavr_wrap.cxx -c simulavr.so: $(TCL_OBJECTS) $(CXX) $(CXXFLAGS) $(TCL_OBJECTS) -ltcl$(TCL_VERSION) $(BFD)/bfd/libbfd.a $(BFD)/libiberty/libiberty.a -lc -lm -lncurses -shared -o simulavr.so
#define ZUHAUSE #define PRG_WISH "/usr/bin/wish" #ifndef ZUHAUSE #define BFD_H "/home/user/rudolphk/avrdownload/binutils-2.14/bfd/bfd.h" #else #define BFD_H "/home/zfrdh/avrdownload/binutils-041230/bfd/bfd.h" #endif #define VERSION "0.0000001 local version " #ifdef __DO_NOT_USE_FROM_C_CODE #if swig is available all: simulavr simulavr.so #else swig is not availabe #all: simulavr #endif #if ccache is available CXX=ccache g++ #else # CXX= g++ #endif #some systems have no libtcl.so, they use libtcl8.4 instead so please set TCL_VERSION #it is allowed to leave TCL_VERSION TCL_VERSION=8.4 #TCL_VERSION= #ifndef ZUHAUSE #BFD= /home/user/rudolphk/avrdownload/binutils-2.14 #else BFD= /home/zfrdh/avrdownload/binutils-041230 #endif #endif | http://lists.gnu.org/archive/html/avr-libc-dev/2007-09/msg00030.html | CC-MAIN-2018-26 | refinedweb | 1,328 | 70.09 |
Doing extravehicular activity on Dev Space | Mainly focused on Python🐍 and ML🤖 but love React also
In this post we are going to build a web application which will compare the similarity between two documents. We will learn the very basics of natural language processing (NLP) which is a branch of artificial intelligence that deals with the interaction between computers and humans using the natural language.
Let's start with the base structure of program but then we will add graphical interface to making the program much easier to use. Feel free to contribute this project in my GitHub.
NLTK and Gensim we are going to use. It contains text processing libraries for tokenization, parsing, classification, stemming, tagging and semantic reasoning.
G)
Topic models and word embedding are available in other packages like scikit, R etc. But the width and scope of facilities to build and evaluate topic models are unparalleled in gensim, plus many more convenient facilities for text processing. Another important benefit with gensim is that it allows you to manage big text files without loading the whole file into memory.
First, let's install nltk and gensim by following commands:
pip install nltk pip install gensim
Tokenization of words (NLTK)
We use the method word_tokenize() to split a sentence into words. Take a look example below
from nltk.tokenize import word_tokenize data = "Mars is approximately half the diameter of Earth." print(word_tokenize(data))
Output:
['Mars', 'is', 'approximately', 'half', 'the', 'diameter', 'of', 'Earth']
Tokenization of sentences (NLTK)
An obvious question in your mind would be why sentence tokenization is needed when we have the option of word tokenization. We need to count average words per sentence, so for accomplishing such a task, we use sentence tokenization as well as words to calculate the ratio.
from nltk.tokenize import sent_tokenize data = "Mars is a cold desert world. It is half the size of Earth. " print(sent_tokenize(data))
Output:
['Mars is a cold desert world', 'It is half the size of Earth ']
Now, you know how these methods is useful when handling text classification. Let's implement it in our similarity algorithm.
Open file and tokenize sentences
Create a .txt file and write 4-5 sentences in it. Include the file with the same directory of your Python program. Now, we are going to open this file with Python and split sentences.
import nltk from nltk.tokenize import word_tokenize, sent_tokenize file_docs = [] with open ('demofile.txt') as f: tokens = sent_tokenize(f.read()) for line in tokens: file_docs.append(line) print("Number of documents:",len(file_docs))
Program will open file and read it's content. Then it will add tokenized sentences into the array for word tokenization.
Tokenize words and create dictionary
Once we added tokenized sentences in array, it is time to tokenize words for each sentence.
gen_docs = [[w.lower() for w in word_tokenize(text)] for text in file_docs]
Output:
[['mars', 'is', 'a', 'cold', 'desert', 'world', '.'], ['it', 'is', 'half', 'the', 'size', 'of', 'earth', '.']]
In order to work on text documents, Gensim requires the words (aka tokens) be converted to unique ids. So, Gensim lets you create a Dictionary object that maps each word to a unique id. Let's convert our sentences to a [list of words] and pass it to the corpora.Dictionary() object.
dictionary = gensim.corpora.Dictionary(gen_docs) print(dictionary.token2id)
Output:
{'.': 0, 'a': 1, 'cold': 2, 'desert': 3, 'is': 4, 'mars': 5, 'world': 6, 'earth': 7, 'half': 8, 'it': 9, 'of': 10, 'size': 11, 'the': 12}
A dictionary maps every word to a number. Gensim lets you read the text and update the dictionary, one line at a time, without loading the entire text file into system memory.
Create a bag of words
The next important object you need to familiarize with in order to work in gensim is the Corpus (a Bag of Words). It is a basically object that contains the word id and its frequency in each document (just lists the number of times each word occurs in the sentence).
Note that, a ‘token’ typically means a ‘word’. A ‘document’ can typically refer to a ‘sentence’ or ‘paragraph’ and a ‘corpus’ is typically a ‘collection of documents as a bag of words’.
Now, create a bag of words corpus and pass the tokenized list of words to the Dictionary.doc2bow()
Let's assume that our documents are:
Mars is a cold desert world. It is half the size of the Earth.
corpus = [dictionary.doc2bow(gen_doc) for gen_doc in gen_docs]
Output:
{'.': 0, 'a': 1, 'cold': 2, 'desert': 3, 'is': 4, 'mars': 5, 'world': 6, 'earth': 7, 'half': 8, 'it': 9, 'of': 10, 'size': 11,'the': 12} [[(0, 1), (1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1)], [(0, 1), (4, 1), (7, 1), (8, 1), (9, 1), (10, 1), (11, 1), (12, 2)]]
As you see we used "the" two times in second sentence and if you look word with id=12 (the) you will see that its frequency is 2 (appears 2 times in sentence)
TFIDF
Term Frequency – Inverse Document Frequency(TF-IDF) is also a bag-of-words model but unlike the regular corpus, TFIDF down weights tokens (words) that appears frequently across documents.
Tf-Idf is calculated by multiplying a local component (TF) with a global component (IDF) and optionally normalizing the result to unit length. Term frequency is how often the word shows up in the document and inverse document frequency scales the value by how rare the word is in the corpus. In simple terms, words that occur more frequently across the documents get smaller weights.
This is the space. This is our planet. This is the Mars.
tf_idf = gensim.models.TfidfModel(corpus) for doc in tfidf[corpus]: print([[mydict[id], np.around(freq, decimals=2)] for id, freq in doc])
Output:
[['space', 0.94], ['the', 0.35]] [['our', 0.71], ['planet', 0.71]] [['the', 0.35], ['mars', 0.94]]
The word ‘the’ occurs in two documents so it weighted down. The word ‘this’ and 'is' appearing in all three documents so removed altogether.
Creating similarity measure object
Now, we are going to create similarity object. The main class is Similarity, which builds an index for a given set of documents.The Similarity class splits the index into several smaller sub-indexes, which are disk-based. Let's just create similarity object then you will understand how we can use it for comparing.
# building the index sims = gensim.similarities.Similarity('workdir/',tf_idf[corpus], num_features=len(dictionary))
We are storing index matrix in 'workdir' directory but you can name it whatever you want and of course you have to create it with same directory of your program.
NOTE: Please don't forget to create 'workdir' file. Otherwise it will cause errors.
Create Query Document
Once the index is built, we are going to calculate how similar is this query document to each document in the index. So, create second .txt file which will include query documents or sentences and tokenize them as we did before.
file2_docs = [] with open ('demofile2.txt') as f: tokens = sent_tokenize(f.read()) for line in tokens: file2_docs.append(line) print("Number of documents:",len(file2_docs)) for line in file2_docs: query_doc = [w.lower() for w in word_tokenize(line)] query_doc_bow = dictionary.doc2bow(query_doc) #update an existing dictionary and create bag of words
We get new documents (query documents or sentences) so it is possible to update an existing dictionary to include the new words.
Document similarities to query
At this stage, you will see similarities between the query and all index documents. To obtain similarities of our query document against the indexed documents:
# perform a similarity query against the corpus query_doc_tf_idf = tf_idf[query_doc_bow] # print(document_number, document_similarity) print('Comparing Result:', sims[query_doc_tf_idf])
Cosine measure returns similarities in the range (the greater, the more similar).
Consider following documents:
Mars is the fourth planet in our solar system. It is second-smallest planet in the Solar System after Mercury. Saturn is yellow planet.
and query document is:
Saturn is the sixth planet from the Sun.
Output:
[0.11641413 0.10281226 0.56890744]
As a result, we can see that third document is most similar
Average Similarity
What's next? I think it is better to calculate average similarity of query document. At this time, we are going to import numpy to calculate sum of these similarity outputs.
import numpy as np sum_of_sims =(np.sum(sims[query_doc_tf_idf], dtype=np.float32)) print(sum_of_sims)
Numpy will help us to calculate sum of these floats and output is:
# [0.11641413 0.10281226 0.56890744] 0.78813386
To calculate average similarity we have to divide this value with count of documents:
percentage_of_similarity = round(float((sum_of_sims / len(file_docs)) * 100)) print(f'Average similarity float: {float(sum_of_sims / len(file_docs))}') print(f'Average similarity percentage: {float(sum_of_sims / len(file_docs)) * 100}') print(f'Average similarity rounded percentage: {percentage_of_similarity}')
Output:
Average similarity float: 0.2627112865447998 Average similarity percentage: 26.27112865447998 Average similarity rounded percentage: 26
Now, we can say that query document (demofile2.txt) is 26% similar to main documents (demofile.txt)
What if we have more than one query documents?
As a solution, we can calculate sum of averages for each query document and it will give us overall similarity percentage.
Assume that our main document are:
Malls are great places to shop, I can find everything I need under one roof. I love eating toasted cheese and tuna sandwiches. Should we start class now, or should we wait for everyone to get here?
By the way I am using random word generator tools to create these documents. Anyway, our query documents are:
Malls are goog for shopping. What kind of bread is used for sandwiches? Do we have to start class now, or should we wait for everyone to come here?
Let's see the code:
avg_sims = [] # array of averages # for line in query documents for line in file2_docs: # tokenize words query_doc = [w.lower() for w in word_tokenize(line)] # create bag of words query_doc_bow = dictionary.doc2bow(query_doc) # find similarity for each document query_doc_tf_idf = tf_idf[query_doc_bow] # print (document_number, document_similarity) print('Comparing Result:', sims[query_doc_tf_idf]) # calculate sum of similarities for each query doc sum_of_sims =(np.sum(sims[query_doc_tf_idf], dtype=np.float32)) # calculate average of similarity for each query doc avg = sum_of_sims / len(file_docs) # print average of similarity for each query doc print(f'avg: {sum_of_sims / len(file_docs)}') # add average values into array avg_sims.append(avg) # calculate total average total_avg = np.sum(avg_sims, dtype=np.float) # round the value and multiply by 100 to format it as percentage percentage_of_similarity = round(float(total_avg) * 100) # if percentage is greater than 100 # that means documents are almost same if percentage_of_similarity >= 100: percentage_of_similarity = 100
Output:
Comparing Result: [0.33515707 0.02852172 0.13209888] avg: 0.16525922218958536 Comparing Result: [0. 0.21409164 0.27012902] avg: 0.16140689452489218 Comparing Result: [0.02963242 0. 0.9407785 ] avg: 0.3234703143437703
We had 3 query documents and program computed average similarity for each of them. If we calculate these values, result will:
0.6501364310582478
We are formatting the value as percentage by multiplying it with 100 and rounding it to make a value simpler. The final result with Django:
Add SMS, calling to apps in your favorite language | https://hackernoon.com/compare-documents-similarity-using-python-or-nlp-0u3032eo | CC-MAIN-2022-27 | refinedweb | 1,858 | 56.55 |
Kid: Adding a New Language to Komodo with UDL
-1. This Tutorial doesn’t work with Komodo 4.2
The API changed slightly when 4.2 was released, but wasn’t quite correct. We’re working on getting it operational again. Apologies for any inconvenience.
This tutorial works best with two zip files. You’ll find the first one in your Komodo install area, at outside the Komodo install area, since we’ll be reusing many of the files we ship, or making slight modifications to them.
Then download kid.zip, which contains a final version of the files this tutorial walks you through. The first zip/tgz file creates a directory called “luddite-1.0.0”. Copy the kid.zip file into that directory, and unzip it by running unzip -a kid.zip.
For those who prefer shell commands:
$ mkdir -p ~/play # scratch directory $ cd ~/play $ tar xfz komodo-installdir/lib/support/luddite/luddite.tar.gz $ cd luddite-1.0.0 $ wget $ unzip -a kid.zip
It’s well-understood that a template-based system is a better way of delivering web content than writing pure code. Tasks are broken down into separate files, so the programmers can work on code, the writers in HTML or XML, and the designers with CSS. Usually you need a few files to glue together the various pieces. The concept is still new enough that there is no universal agreement on a name for the nature of the contents of these glue files, but “template languages” seems to be the most common.
When we started work on Komodo, around 2000, PHP was the only commonly-used open template language (“open” allows me to leave proprietary systems like JSP, ASP, and ColdFusion out of the discussion). The editor Komodo is based on, Scintilla, actually bundles HTML and PHP processing in the same colorizing module. But over the years we saw new multi-component languages get released, and enthusiastic users discovering that this was exactly what they needed to deliver dynamic web content quickly. During the last couple of years we’ve seen near-instant uptake of emerging high-level frameworks like Rails, Django, and CakePHP.
These template languages are relatively easy to build. Put together an XML or HTML parser, maybe an XPath processor, and a language that has an eval() statement, and you have an instant template language (if one that is inherently insecure, with that eval statement. If the language can be freely embeddable in a web server like Apache, so much the better. Replace the eval() statement with pattern-matching and a managed symbol table, and you have something other people can use.
So we envision that increasingly more template languages will be created. Communities of avid fans will grow around them, and some of them will be looking for a GUI-type editor to manage them in.
Now we knew that the Scintilla HTML/PHP lexer wouldn’t be satisfactory for all these other template languages. These lexers are important parts of Komodo. They’re invoked on almost every keystroke, and they try to update the style of each visible character as quickly as possible.
Previously, we had two options to support new languages:
- make a modification to the HTML/PHP lexer (it currently also has some support for ASP, VBScript, and Embedded Python), and associate new languages with it
- write a new lexer
Neither solution was very attractive. Template languages can be complex, with many edge cases that we wanted to handle well. Each template language can have a few idiosyncracies, and it’s important to handle them correctly to create a smooth editing experience.
Meanwhile, most template languages also have many common features. They all have a markup base, which we could safely assume to be XML, XHTML, or HTML. If they’re (X)HTML-based, they should support embedded CSS and JavaScript. They usually embed a “server-side language” (“SSL” for short) — this is the code that is run on the server, emitting the HTML at run-time. And they all have transition points that indicate when to move from HTML to the SSL, and when to return. Some of them even have their own little language on top of the SSL — Perl’s Template-Toolkit and Smarty/PHP are two common examples.
The other problem with either of those two approaches was that they both entailed a rebuild of Komodo, which meant that a new feature wouldn’t be available until the next release. We wanted to make this a Komodo extension point, so someone using a language like Liquid 1 would be able to add an extension to Komodo, and take advantage of as many language-aware features in Komodo as possible. This obviously covered syntax coloring, but we wanted to include auto-indenting, code-folding, selection-commenting, and as much as possible, code-completion. We did achieve all of the above, and are working out how to provide hooks to Komodo’s syntax checking and debugging sub-systems for a future release.
And we wanted people to be able to do this without having to know anything about Scintilla, how lexers work, or even access to a C++ compiler.
I had done enough work with two complicated lexers, for Perl and Ruby, and fixed bugs in various others, that I saw recurring patterns in lexers that every language needed to implement. Some of these patterns were simple (comments start with “#” or “//”, and end at the end of line; numeric constants start with a digit, and have an optional fractional and exponent part); some were more complex (strings in Perl can start with “q” followed by a non-alphanumeric character, and end with that same character, but don’t forget to handle backslash escapes; “old-style” HTML attribute values are not always quoted); some were hard enough that we haven’t implemented them yet (here-documents). But what I did see was that all these lexers could be implemented by specifying a set of patterns that are applicable at certain states.
We set out to design a language that would let people focus on the high-level aspect of building these lexers: first break up each template language into a set of sub-languages, called families. Then break up each family into a set of states (are we in a comment, string, or numeric constant)? And finally assign to each state a set of patterns we’re looking for, with actions to perform when one of them matches. These actions would assign styles to a range of text, and possibly move to a different state.
Then we needed a way of getting this information into Komodo. Conveniently enough, we introduced a Firefox-like extension mechanism with version 4. The idea was to take this high-level description of a new language, and run it through a process that would create a .xpi file (or cross-platform installer, pronounced “zippy”). Add it to Komodo, and you’d have integrated your new language.
This technology is called UDL, for User-Defined Languages. UDL consists of three parts:
- a language called Luddite (for “Language for User-DefineD Integrated TEmplating systems”, of course), that is used to specify lexers
- a general-purpose lexer engine added to Scintilla, which converts compiled Luddite programs into screens full of syntax-highlighted code
- a XPI-generator tool
Komodo also ships with the source for all its UDL-based languages. You’ll find it in either , since we’ll be reusing many of the files we ship, or making slight modifications to them. If you find you’re typing a lot as you work through this tutorial, you probably didn’t read this paragraph.
2. Creating a New Lexer for Kid
This article is intentionally different from the documentation you’ll find in the Komodo help pages. UDL and Luddite have served us well here at ActiveState — writing a lexer for Liquid would take a few minutes.
But we intended UDL to be usable by people who didn’t also design it. Short of hitting the road, we’ve written this document as if you’re working side by side with us. We’ll make typos early on, run into error messages and situations that don’t work the way we want them to, diagnose the problems, and fix them.
One of our beta testers for Komodo 4 asked us when we were going to deliver syntax coloring for Kid. At first we thought this would be a good test for UDL — was the technology mature enough, and the documentation thorough enough — that a third party could succeed with it? It seemed like a good test case; none of us had heard of Kid, but no one else outside the company was delivering a lexer. Since we needed both a tutorial and a lexer for Kid, it seemed like an ideal case study.
The code samples in this document are different from the ones in the accompanying zip file. The zipped files are final, correct versions of the UDL code needed to implement Kid. The code snippets in this document contain several errors (some of which are intentional), so I could cover the error detection and correction process as well. Luddite’s a young language, and this particularly shows in its error detection capabilities. Also, when you’re targeting a GUI, sometimes the only indication of an error situation is silence. We’ll see a few of those, so we’ll show you where to look for clues, and how to put them together to solve the puzzle.
2.1 A Spec for a Kid Lexer
First, keep in mind that most of the work of building a Kid lexer has already been done. It’s based on XHTML, and Komodo ships with standalone lexers for HTML, JavaScript, and CSS, as well as modules that cover the transitions among these three languages (simplified because CSS and JavaScript don’t directly interact).
So the next step was to find the description of the Kid language (at 2, and determine the remaining tasks we’re faced with. From this page we see that Kid files consist of familiar HTML files with four places where Python code can appear:
- Between “python” processing-instructions (PIs): <?python … ?>. I downloaded the Kid source code, and saw that Kid works by reading an XHTML file with the ElementTree XML parser, doing a generic XML parse on it, and then finding the Python-specific parts after. So this means that because the XML parser doesn’t know about Python strings and comments, the first occurrence of “?>” will end a Python PI. We’ll want to implement our lexer to model this behavior.
- Attributes in the “” namespace are deemed to contain Python code. Luddite currently isn’t namespace-aware, so we’ll assume that the “py” prefix always maps to this namespace. Komodo bug 53517 tracks this item.
- In any non-py attribute, or in text content, sequences of “${...}” contain Python expressions. “$$” is the escape sequence for a single ‘$‘.
- Any expression starting with a ‘$‘, followed by ‘.‘-separated identifiers, should be treated as a Python expression. I assumed the ‘$‘ had to be preceded by a non-identifier, although the code didn’t make that check, as of version 0.9.4. Making the check complicated the code, and I initially got it wrong, which led to a couple of useful lessons while testing the extension. So I left it in.
$-expansion is turned off inside XML comments. The exception is for comments that start with “[” or “<![“, or comments that end with “//“. Luddite rules are constrained to one line at a time, so we won’t be able to handle the final situation. But the JavaScript and CSS modes are already relatively intelligent about these compatibility hacks. The Luddite code accepts CDATA and XML-comment delimiters in these states, colors them as comments, and then stays in each family’s default state. You can try it in Komodo right now. Bring up an HTML file, add a script tag anywhere, and wrap the contents with either CDATA marked sections or XML comments. Neither will affect the JavaScript highlighting.
Here’s an outline of everything we expect to see working once we finish the lexer. We of course test to make sure we don’t get Python lexing outside the Python areas, and make sure that other features, such as auto-indentation, are working.
- <?python ... ?> – kwd ident op strings
- <?pytho ... ?> – verify failure
- <?python2 ... ?> – verify failure
- <?python* ... ?> – rejected by ElementTree (Kid’s parser).
- python content attributes:
- double-quoted: verify types of tokens, single-quoted single and triple strings, and escape chars.
- single-quoted: similar
- ${...}:
- on in normal attribute strings
- off in Python content attributes – test by putting a string inside a string e.g.: print “this is a stri${"inner string"}ng” “inner” and “string” should be colored as identifiers
- on in text content
- off in comments
- off in PIs
- off in CDATA sections
- on in JavaScript code
- on in CSS styles
- $[...]: off
- $$ works as an escape wherever ${…} is on
- $foo.bar:
- on in normal attribute strings
- off in Python content attribute strings
- on in text content
- off in comments
- off in PIs
- off in CDATA sections
- on in JavaScript code
- on in CSS styles
- auto-indentation:
- works for HTML
- works for CSS
- works for JavaScript
- works for Python
- Code|Comment Region (and uncomment):
- works for HTML
- works for CSS
- works for JavaScript
- works for Python
- code-completion:
- works for HTML, CSS sections
- multi-language Python code-completion wasn’t ready for Komodo 4.0 (and due to the way we implemented multi-language completion, JavaScript isn’t ready in Python-based UDLs).
Since I said we wouldn’t be typing much, let’s look at the *-mainlex.udl files in the work directory, and pick a promising starting point. The django-mainlex.udl file is a red herring; Django is implemented in Python, and works well with it, but Django template files don’t contain any Python code. Let’s open up the rhtml-mainlex.udl file instead 3 4.
The rhtml-mainlex.udl file defines the name of the language, which will show up in the Komodo UI. This field is case-sensitive, and all language names are normally either all-caps for acronyms, or capitalized otherwise.
The rest of the file contains includes for the components that contain an RHTML file. The good news is that we can use all the ones that don’t contain “ruby” or “rhtml” in their names. Our “mainlex.udl” file will contain include statements on all these files:
include "html2js.udl" include "html2css.udl" include "css2html.udl" include "js2html.udl" include "html.udl" include "csslex.udl" include "jslex.udl"
With that list, we have a working spec for an HTML lexer. By no coincidence, this is the full list of includes used for the html-mainlex.udl file.
So now we need to add Luddite files to cover the transitions from HTML, JavaScript, and CSS into Python, and back out. And we’ll need a file to describe the core Python lexer as well. Our final kid-mainlex.udl file will then look like this:
language Kid
include “html2js.udl”
include “html2css.udl”
include “kid/html2python.udl” #*
include “kid/css2python.udl” #*
include “css2html.udl”
include “kid/js2python.udl” #*
include “js2html.udl”
include “kid/python2html.udl” #*
include “html.udl”
include “csslex.udl”
include “jslex.udl”
include “pythonlex.udl” #*
The files that need to be written have a “#*” comment. The transition files are going in the “kid” subdirectory to avoid future collisions with transition rules for other Python-based template languages we might want to support.
So let’s work down the list. First we’ll look at the html2ruby.udl file to get an idea of what we need to do to handle Python:
# html2ruby.udl family markup
# Precondition: we already painted everything before the
# ‘<‘ that brought us here.
state IN_M_STAG_EXP_TNAME:
‘%#’ : => IN_TPL_BLOCK_COMMENT_1
/%=?/ : paint(include, TPL_OPERATOR), spush_check(IN_M_DEFAULT) => IN_SSL_DEFAULT
state IN_M_STAG_ATTR_DSTRING:
/<%=?/ : paint(upto, M_STRING), paint(include, TPL_OPERATOR), spush_check(IN_M_STAG_ATTR_DSTRING) => IN_SSL_DEFAULT
state IN_M_STAG_ATTR_SSTRING:
/<%=?/ : paint(upto, M_STRING), paint(include, TPL_OPERATOR), spush_check(IN_M_STAG_ATTR_SSTRING) => IN_SSL_DEFAULT
The html2ruby.udl file also contains code to handle RHTML comments. Kid doesn’t have those, so I removed that part.
Recall that at its essense, Luddite code describes a state machine. You give each state an arbitrary name, specify which strings and patterns to match when we’re in that state, and a list of commands specifying what to do next. The two most common commands are “paint” and “=>”, which specifies the state to change to. If no actions are given, UDL stays in the same state, starting at the character following the matched sequence. If no conditions in a given state fires, UDL consumes the current character, and moves on to the next.
The paint action needs a bit of explanation as well. paint(upto... means assign all the unassigned text to the point where the current match started the specified style (like the “M_STRING” above). paint(include...) gives all the text up to and including the current match the style.
State names are created when first mentioned. The line “state FOO:” introduces a state declaration for state FOO, and is followed by one or more state conditions. State names are global, and states may be defined in one or more places. States are “used” when an action specifies a state to change to. Luddite will complain about undefined states, and give a warning message about defined states that are never used.
The state conditions are attempted in the order specified in the main Luddite program, flattening out included files. Once one condition is fulfilled, no others are attempted. This is why matches on longer strings and patterns should be attempted before trying to match shorter strings that could be a prefix of the longer one. For the same reason, transition files should be included before the main files (e.g. the files html2js.udl and js2html.udl are included before html.udl and jslex.udl above).
One way of writing faster parsers is to provide an explicit character set to skip over, such as in this state:
state BREAKFAST: 'juice' : ... 'coffee' : ... 'milk' : ... /[^cjm]+/ : #stay here
The other all-caps names in Luddite are conventionally used for Scintilla style names. These are defined here in Appendix 1. The “SCE_UDL_” prefix on these names is optional. Luddite allows states to have the same name as style names (with or without the prefix), but the practice isn’t recommended.
So we can easily support the <?python… form, by replacing
state IN_M_STAG_EXP_TNAME: '%#' : => IN_TPL_BLOCK_COMMENT_1 /%=?/ : paint(include, TPL_OPERATOR), spush_check(IN_M_DEFAULT) => IN_SSL_DEFAULT
with this code:
state IN_M_STAG_EXP_TNAME: /\?python\b/ : paint(include, TPL_OPERATOR), spush_check(IN_M_DEFAULT) => IN_SSL_DEFAULT
“SSL_DEFAULT” is the conventional name for the state where each sequence of server-side code starts.
The spush_check action is for the point where we find a “?>” that ends the <?python block. At that point we emit an spop_check action, and it will go back to the IN_M_DEFAULT state (which is conventionally the starting state for the markup sub-language).
We need to handle $-expansion here as well. This can happen in attribute values and text content, and I’m going to assume the attribute values must be quoted, as Kid is XHTML-based. So we can borrow some of the html2ruby code, and replace accordingly. We have to handle single-quoted and double-quoted strings separately, which is a cry for further encapsulation in this language, but we’ll manage:
state IN_M_STAG_ATTR_DSTRING: '$' : #stay here, this is an escape sequence '${' : paint(upto, M_STRING), paint(include, SSL_OPERATOR), \ spush_check(IN_M_STAG_ATTR_DSTRING) => IN_SSL_DEFAULT # **todo** dotted identifiers
state IN_M_STAG_ATTR_SSTRING:
‘$$’ : #stay here, this is an escape sequence
‘${‘ : paint(upto, M_STRING), paint(include, SSL_OPERATOR), \
spush_check(IN_M_STAG_ATTR_SSTRING) => IN_SSL_DEFAULT
# **todo** dotted identifiers
We also said we’d support $-interpolated Python in text content as well. Text content isn’t actually handled explicitly in the markup-base.udl file. Instead, whenever we find some markup when we’re in the IN_M_DEFAULT state, we color everything up to that character with the M_DEFAULT style, and then usually switch to a different state. So text content will be in that state, leading to this rule:
state IN_M_DEFAULT: '$' : #stay here, this is an escape sequence '${' : paint(upto, M_DEFAULT), paint(include, SSL_OPERATOR), \ spush_check(IN_M_DEFAULT) => IN_SSL_DEFAULT # **todo** dotted identifiers
Now we’re going to use the UDL stack to handle “}”. Standard Python has braces, so we use the stack to determine whether to bounce back into markup mode, or stay here.
There is no Python lexer yet (one of the reasons for choosing Kid in this tutorial was to show how to write a complete lexer for a server-side language), but it will need these two rules in the default state:
state IN_SSL_DEFAULT: '{' : paint(upto, SSL_DEFAULT), paint(include, SSL_OPERATOR), \ spush_check(IN_SSL_DEFAULT), => IN_SSL_DEFAULT '}' : paint(upto, SSL_DEFAULT), paint(include, SSL_OPERATOR), \ spop_check, => IN_SSL_DEFAULT
So when we find a “{” in Python, we push the SSL_DEFAULT state on the state-stack. And when we find a “}” at the default state, we check the state-stack. If it’s non-empty, we switch to its top state, and pop it off the stack. Otherwise we go to the target state.
Since the standard Python lexer doesn’t need to do anything special with braces, we’ll override handling them, and put them in a separate section of kid/html2python.udl.
We’ll also process the unbracketed form in the html2python.udl file, although strictly speaking it belongs to python. First we need to recognize when we enter the state:
pattern PYHTMLDOLLARSTART = '(?<^|[^\w_\$])\$(?=[\w_])'
state IN_M_STAG_ATTR_DSTRING:
/$PYHTMLDOLLARSTART/ : paint(upto, M_STRING), \
paint(include, SSL_OPERATOR), spush_check(IN_M_STAG_ATTR_DSTRING),
=> IN_M_PYTHON_UNBRACKETED_EXPN
state IN_M_STAG_ATTR_SSTRING:
/$PYHTMLDOLLARSTART/ : paint(upto, M_STRING), \
paint(include, SSL_OPERATOR), spush_check(IN_M_STAG_ATTR_SSTRING),
=> IN_M_PYTHON_UNBRACKETED_EXPN
state IN_M_DEFAULT:
/$PYHTMLDOLLARSTART/ : paint(upto, M_DEFAULT), \
paint(include, SSL_OPERATOR), => IN_M_PYTHON_UNBRACKETED_EXPN
While we could let bracketed expressions be handled by our regular SSL states, we need to handle unbracketed expressions explicitly:
state IN_M_PYTHON_UNBRACKETED_EXPN: '.' : paint(upto, SSL_IDENTIFIER), paint(include, SSL_OPERATOR) /[^\W_]/: paint(upto, SSL_IDENTIFIER), spop_check, => IN_M_DEFAULT /\z/ : paint(include, SSL_IDENTIFIER)
We’ve been introducing new concepts as we go along. The pattern declaration allows us to give commonly used patterns a name. Each family has its own set of pattern names, so you can specify that “-” is a markup NAMECHAR, but not a CSL NAMECHAR.
Incidentally, the pattern matching is implemented with the PCRE perl-compatible, regular-expression library. This tutorial assumes you’re comfortable with this syntax. If not, and you’re sure you want to master Luddite, start at the Mastering Regular Expressions site, choose a (natural) language and a vendor, and get that book.
The /\z/ pattern matches the end of the buffer. Usually Luddite can figure out what color to apply to all pending characters at the end of the buffer. Where more than one color is used in a state, as in this case, it’s always safe to specify an explicit EOF color. If a lexer doesn’t color the remaining characters in the buffer, the scintilla component will repeatedly invoke the lexer trying to discover the styles for these characters, reducing performance.
Finally we need to handle the py: attributes. Because Luddite doesn’t have named variables, supporting both types of quoted attribute strings is going to be a bit hard. But this problem has already been solved for the arbitrary string and regex delimiters used in languages like Perl and Ruby. When we find the quote character, we set the delimiter, and we’ll add a default level rule for the Python side to recognize that delimiter.
The new rules will be:
state IN_M_STAG_POST_TAGNAME: # you need to read markup-base.udl to find this state /py:[$CS]+/ : paint(upto, M_TAGSPACE), paint(include, M_ATTRNAME), => IN_M_KID_PYATTR_1
I’m going to assume the attribute name, ‘=’, and initial quote are on the same line. You can add more conditions to allow multi-line attributes.
state IN_M_KID_PYATTR_1: '=' : paint(upto, M_TAGSPACE), paint(include, M_OPERATOR) => IN_M_KID_PYATTR_2 /[$WS]/ : #stay /[^'"]/ : paint(upto, M_TAGSPACE), IN_M_DEFAULT
state IN_M_KID_PYATTR_2:
/([‘”])/ : paint(upto, M_TAGSPACE), paint(include, M_STRING), set_delimiter(1), \
=> IN_SSL_DEFAULT
and we add one rule to python2html.udl:
state IN_SSL_DEFAULT: delimiter: paint(include, SSL_DEFAULT), => IN_M_STAG_POST_TAGNAME
The delimiter mechanism was designed with Ruby and Perl in mind, certainly not for Python, or a Python-derived language. It turns out that delimiters can be used to handle single-quoted and double-quoted strings with one set of rules, when the two kinds of strings are identical. For example, single- and double-quoted strings are identical in JavaScript, CSS, Python, and *ML attribute values; in Perl, Ruby, and PHP double-quoted strings support interpolate expressions, while single-quoted strings don’t. I haven’t moved to replace the current string handling with delimiters because they don’t nest (yet another work item).
At this point we’ve finished html2python.udl. Let’s move on to the js2python part. Now there is no js2ruby.udl file (there probably should be though). So we’ll look at js2php.udl. It has two rules, one for handling transitions to PHP inside JavaScript single-quoted strings, and one for transitions in double-quoted strings.
So the contents of kid/js2python.udl should look familiar:
state IN_CSL_DSTRING: '$' : #escape, stay '${' : paint(upto, CSL_STRING), paint(include, SSL_OPERATOR), \ spush_check(IN_CSL_DSTRING) => IN_SSL_DEFAULT
state IN_CSL_SSTRING:
‘$$’ : #escape, stay
‘${‘ : paint(upto, CSL_STRING), paint(include, SSL_OPERATOR), \
spush_check(IN_CSL_SSTRING) => IN_SSL_DEFAULT
state IN_CSL_DEFAULT:
‘$$’ : #escape, stay
‘${‘ : paint(upto, CSL_DEFAULT), paint(include, SSL_OPERATOR), \
spush_check(IN_CSL_DEFAULT) => IN_SSL_DEFAULT
We aren’t going to support the unbracketed form, because the “$” is a valid identifier character in JavaScript, and with the wide adoption of libraries like prototype.js, the use of “$” signs in JavaScript code has become more common.
Supporting ${...} in JavaScript’s two kinds of comments is left as the proverbial exercise for the reader. Since the comments will only be seen by the JavaScript interpreter, and then ignored, I don’t see the point of interpolating variables there anyway.
The kid/css2python.udl file is almost identical to the js2python one. Again, we allow for interpolation outside strings, except in comments, and we again wish we had a better encapsulation mechanism:
state IN_CSS_DSTRING: '$' : #escape, stay '${' : paint(upto, CSS_STRING), paint(include, SSL_OPERATOR), \ spush_check(IN_CSS_DSTRING) => IN_SSL_DEFAULT
state IN_CSS_SSTRING:
‘$$’ : #escape, stay
‘${‘ : paint(upto, CSS_STRING), paint(include, SSL_OPERATOR), \
spush_check(IN_CSS_SSTRING) => IN_SSL_DEFAULT
state IN_CSS_DEFAULT:
‘$$’ : #escape, stay
‘${‘ : paint(upto, CSS_DEFAULT), paint(include, SSL_OPERATOR), \
spush_check(IN_CSS_DEFAULT) => IN_SSL_DEFAULT
Again, we don’t need to handle the case of reaching the end of the Python expression, because when we reach the “}”, we’ll pop the correct destination state off the state stack.
One of the CSS experts out there will say we aren’t done. CSS allows unquoted URLs inside the url() operator. Fine. By looking for ‘url’ in csslex.udl, we see that unquoted URLs are handled in the IN_URL_2 state. The rest should be easy:
state IN_URL_2: '$' : #escape, stay '${' : paint(upto, CSS_DEFAULT), paint(include, SSL_OPERATOR), \ spush_check(IN_URL_2) => IN_SSL_DEFAULT
The python2html.udl file has only one task, to get back to the markup family on “?>”. Because the HTML parser doesn’t know that the contents of the PI are actually Python code, we have to model the parser, and use coloring to let the programmer know how the document will be interpreted.
family ssl
state IN_SSL_DEFAULT:
‘?>’ : paint(upto, SSL_DEFAULT), paint(include, SSL_OPERATOR), => IN_M_DEFAULT
state IN_SSL_SSTRING:
‘?>’ : paint(upto, SSL_STRING), paint(include, SSL_OPERATOR), => IN_M_DEFAULT
state IN_SSL_DSTRING:
‘?>’ : paint(upto, SSL_STRING), paint(include, SSL_OPERATOR), => IN_M_DEFAULT
state IN_SSL_TRIPLE_SSTRING:
‘?>’ : paint(upto, SSL_STRING), paint(include, SSL_OPERATOR), => IN_M_DEFAULT
state IN_SSL_TRIPLE_DSTRING:
‘?>’ : paint(upto, SSL_STRING), paint(include, SSL_OPERATOR), => IN_M_DEFAULT
state IN_SSL_COMMENT:
‘?>’ : paint(upto, SSL_COMMENT), paint(include, SSL_OPERATOR), => IN_M_DEFAULT
We’ve now described all the inter-language transitions, but still have to write a lexer for Python. Fortunately, Python is lexically simpler than the other server-side language UDL files. The full text is in pythonlex.udl, but there are some new features worth describing.
Handling Python’s triple-quoted strings is a snap. The only subtlety is remembering that the sequence “\”'” does not end a single-quoted triple-string.
state IN_SSL_DEFAULT:
‘”””‘ : paint(upto, SSL_DEFAULT), => IN_SSL_TRIPLE_DSTRING
‘”‘ : paint(upto, SSL_DEFAULT), => IN_SSL_DSTRING
“”'” : paint(upto, SSL_DEFAULT), => IN_SSL_TRIPLE_SSTRING
“‘” : paint(upto, SSL_DEFAULT), => IN_SSL_SSTRING
state IN_SSL_TRIPLE_DSTRING:
‘\\”‘ : # “”
‘”””‘ : paint(include, SSL_STRING), => IN_SSL_DEFAULT
state IN_SSL_TRIPLE_SSTRING:
“\\'” : # “”
“”'” : paint(include, SSL_STRING), => IN_SSL_DEFAULT
The hard part with single-line strings is processing line-continuations. First, we need to recognize unterminated lines. We need to determine when we reach the end of line, and return to the default state. But if we find a backslash at the end of the line, we need to move to a temporary state that continues the state, and returns to the main string-recognition state as soon as possible.
state IN_SSL_DSTRING /\\[\r\n]/ : => IN_DSL_DSTRING_LINECONT /\\./ : # "" /$/ : paint(upto, SSL_STRING), => IN_SSL_DEFAULT # No EOLString in UDL "'" : paint(upto, SSL_STRING), => IN_SSL_DEFAULT
You might wonder why we can’t simply match /\\$/ and stay in the state. The reason is that UDL will consume the backslash, but end-of-line conditions, as with other zero-width conditions, are not consumable. The UDL engine in fact doesn’t recognize when it’s matched a zero-width pattern and hasn’t changed state, a sure recipe for an infinite loop (it should recognize these, and complain — another bug). This means that when you write a pattern that can succeed without matching one or more character,s you need to move to a different state.
state IN_SSL_DSTRING_LINECONT: /\\[\r\n]/ : #stay /\\./ : => IN_SSL_DSTRING '"' : paint(include, SSL_STRING), => IN_SSL_DEFAULT /./ : => IN_SSL_DSTRING /^$/ : paint(upto, SSL_STRING), => IN_SSL_DEFAULT # End empty lines here
There are five different cases to handle after a backslash-escaped newline:
- Another escaped newline
- A quote ending the string
- An empty line: this triggers a syntax error
- An escaped character (might be a quote), continuing the string
- Any other character continuing the string
Another subtle area is distinguishing periods that start numerals from periods that separate identifiers. This default rule and this state handle that:
/\.(?=[$NMSTART])/ : paint(upto, SSL_DEFAULT), paint(include, SSL_OPERATOR), \ => IN_SSL_IDENTIFIER_1
state IN_SSL_IDENTIFIER_1:
‘.’ : paint(upto, SSL_IDENTIFIER), paint(include, SSL_OPERATOR)
/[^$NMCHAR]/ : paint(upto, SSL_OPERATOR), redo, => IN_SSL_DEFAULT
The redo action tells UDL to not consume the matched string or pattern, and move to the specified string. The Luddite parser will currently complain about a single condition that contains a redo action without a specified state, but it doesn’t detect infinite loops, such as this one:
state STATE_1: 'a' : redo, => STATE_2
state STATE_2:
/\w/ : redo, => STATE_3
state STATE_3:
/[^\d]/ : redo, => STATE_1
If an ‘a’ is encountered at state STATE_1, UDL will normally enter an infinite loop. However the engine has a check: if it notices that it hasn’t moved past a given character after some number of tries, it issues an error message, and moves to the next character. This is not guaranteed to give reasonable results.
Also introduced are the fold statements at the bottom of the module. Each fold statement has three parts – the string to match, the style it has to be colored at, and then a “+” or “-” specifying whether to increase the line’s fold level or decrease it. So for example, if line 10 has a “[” styled as an operator (as opposed to part of a string or comment), and line 12 has a “]”, Komodo will draw a fold box around lines 10 through 12 inclusive.
Komodo actually has a separate way of indicating fold blocks for Python code, based on their indentation level. This makes sense, as indentation in Python reflects program structure. However Luddite doesn’t yet support this.
2.4 A Digression: Why Not Lex?
Lex is a decades-old technology that does the same thing Luddite does — it reads in a stream of characters, and separates them into lexical types. Here’s a string, here’s an identifier, here’s a comment, etc. It’s long been associated with a syntactic analyzer (remember our discussion at the beginning?), which tries to make sense of those separate items. And it mostly uses a list of regular expressions to do its work. A typical Lex program has code like this:
"+" return(PLUS); "-" return(MINUS);
Many other extensible editors take the same approach: to add syntactic coloring for a new language, give a list of patterns to match, with the color for each one.
We originally wanted to do that for UDL, but regular expressions alone are too weak. You can’t use patterns alone to tell a computer that when you’re inside a Ruby double-quoted string, anything between a “#{” and a “}” should be colored as standard Ruby code. And be sure to handle nested occurrences of these strings. And now we’re talking multi-language documents. In RHTML, when we see an instance of “<%=” in an attribute string, we want to step into Ruby mode. When we find the “%>“, we bounce back into HTML mode.
This is impossible to do with regular expressions alone. Then how does Lex do that, you might be asking. The secret with Lex is that right-hand side, after the string or pattern, is actually C code. By wrapping it in braces, you can write arbitrary C, including managing nested states. But we wanted to let people accomplish building lexers for languages like these without having to mess around with C or C++.
3. Building the Extension
To extend Komodo, we need to follow these steps:
- Compile the Luddite program
- Create any other files, and make sure they’re in a correct directory structure
- Package all the files into a XPI
- Add the XPI to Komodo’s extension manager
3.1 Compiling Luddite Files
Let’s assume you’ve unpacked the Komodo Luddite files into a directory called luddite-1.0.0, created the directory luddite-1.0.0/udl/kid, copied the new pythonlex.udl and kid-mainlex.udl files into the udl directory, and the other new files into the udl/kid directory. Change to the luddite-1.0.0 directory. It’s time to build the extension.
We need to compile the specification using this command:
python luddite.py compile -f --ext=.kid.html --guid=9c773798-fbf3-4793-a9f3-43023f53033d --skel udl/kid-mainlex.udl
You can substitute “luddite” for “python luddite.py” on Windows systems, and use “luddite.py” elsewhere. I’m using the full form here, as it’s cross-platform. You can generate your own GUID if you prefer, as long as it matches the class ID used in koKid_UDL_Language.py, which UDL generates.
Komodo uses a convention of giving web-based template languages an extension like “.kid.html”. Since I work with a variety of HTML-based languages, I prefer the two-part extension. If you know that all your HTML files are going to be Kid files, feel free to assign the .html extension to Kid.
Then build the XPI using a command like this:
python luddite.py package -c "creator" --version "major.minor.sub" Kid -f
and then install it. When I ran the output the first time I got this output: ' ' ...
followed by about 30 lines of yacc grammar.
This part of UDL is still rough around the edges. The error mechanism still doesn’t report file names, and we need to reduce the output. The best we can do right now is try compiling each of the files individually, and look for failures. Here’s how it’s done in Windows:
for %i in ( udl\kid\*.udl ) do python luddite.py compile -f %i C...>python luddite.py compile -f udl\kid\css2python.udl yacc: Generating SLR parsing table... yacc: 56 shift/reduce conflicts At least one transition moves to undefined state IN_SSL_DEFAULT This state needs to be defined somewhere. ...
We know there are no errors in this file, as Luddite complains that the state IN_SSL_DEFAULT wasn’t defined. This makes sense, because css2python.udl doesn’t include any other files.
... C...>python luddite.py compile -f udl\kid\html2python.udl '
We see that in html2python.udl line 16 doesn’t end with a backslash, but the state command doesn’t end there (remember that the typos dicussed in the document have been fixed in the actual shipped source). We add it, check over our files for other similar cases (naturally the SSTRING state has the same problem as the DSTRING state, since I copied and pasted it), rerun the command, and get this output:
At least one transition moves to undefined state IN_SSL_SQUOTE This state needs to be defined somewhere.
It turns out that my original single-quote handlers did this:
'"' : paint(upto, SSL_DEFAULT), => IN_SSL_DQUOTE
The target state name should have been the conventional IN_SSL_DSTRING.
The Luddite compiler complains only about the first undefined state. Again, that can be improved.
We rerun the command, and get another undefined state report for IN_DSL_DSTRING_LINECONT. Easy fix for this typo.
Another rerun shows that all referenced state names are now defined, but we have another problem:
luddite: create lexres `build\Kid\lexers\Kid.lexres' Undefined pattern PY in str $PY_HTML_DOLLAR_START, family ssl
I had forgotten that pattern variable names may contain only upper-case names. After a quick change of “PY_HTML_DOLLAR_START” to “PYHTMLDOLLARSTART“, a rebuild gives this result:
yacc: Generating SLR parsing table... yacc: 56 shift/reduce conflicts luddite: create lexres `build\Kid\lexers\Kid.lexres' luddite: create lang service `build\Kid\components\koKid_UDL_Language.py' luddite: create template `build\Kid\templates\All Languages\Kid.kid.html' luddite: create template `build\Kid\templates\Common\Kid.kid.html'
Success!
We’re ready to build the extension.
We run this command:
python luddite.py package -c "Eric Promislow" --version "1.0.0" Kid -f
and get this output:
luddite: create `build\Kid\install.rdf' luddite: create `build\Kid\chrome.manifest' luddite: `kid_language-1.0.0-ko.xpi' successfully created
You can get more help by running “python luddite.py help” for general help, and “python luddite.py help <command>” for help on a specific command.
3.3 Installing and Testing
Find the newly created kid_language-1.0.0-ko.xpi file, and open it with Komodo. You should see two dialog boxes. The first prompts you to install the new extension. If you accept, the second box prompts you to restart Komodo. At this point restart Komodo. This would be a good time to download a sample Kid file to test, if you don’t have any on your local system. I’m using the Mandelbrot set example available at, and saved it in a file called mandelbrot.kid.html. Before installing the XPI, Komodo treats it as an HTML file. One of the ways we can tell that Komodo will color it as a Kid file is when the “def” in the initial Python block is colored like a keyword.
When I restarted Komodo, I found that “def” was still colored like an identifier. In fact, the whole <?python ... ?> block was colored like any HTML PI. And menus like View|View As Language|Other and the File Associations lists in Preferences didn’t have an entry for “Kid”, but the “Kid Language” XPI was listed in the extension manager. The problem was that I forgot to specify the “--guid=GUID” and “--skel” options on the command-line. When I recompiled, repackaged, and reinstalled the XPI, this time there were no bindings. I had to add template files for Komodo to see how to bind the files. In effect, I wanted the XPI components to reside in the subdirectory given below. Files with a “**” to the right are empty files we need to create. All other subdirectories and files are created by the luddite commands.
+---build +---Kid | | chrome.manifest | | install.rdf | | | +---components | | koKid_UDL_Language.py | | | +---lexers | | Kid.lexres | | | +---templates | +---All Languages | | Kid.kid.html ** | | | +---Common | Kid.kid.html ** |
Now when I recompiled, repackaged, and reinstalled, this time “View|View as Language” showed my mandelbrot file was being treated as a Kid file by Komodo, but the coloring doesn’t look as good as we were expecting. The <?python...?> block at the top of the file is colored as if it were a regular processing instruction — switching the buffer’s language from Kid to HTML shows this, although it looks like the contents of the attribute strings are being handled correctly.
So to recap, at this point we’ve figured out how to write a Luddite spec for a lexer that is accepted by the compiler. We’ve also successfully packages the compiled files into a XPI that Komodo will accept, and our changes seem to have been reflected in most of the API. The only thing that isn’t working now is that some of our patterns and states don’t seem to be working.
Currently Luddite doesn’t have a trace mode. Until we build a suitable trace mode (and it will need a detailed configuration controller to prevent the user from getting inundated by hundreds of lines of output on every keypress), it pays to look at the Luddite code that doesn’t seem to be firing.
We know that conditions are attempted in the order they’re encountered. This means that in state IN_M_STAG_EXP_TNAME, /\?python\b/ should be attempted before any of the standard conditions listed in markup-base.udl. However, let’s look at that file to see why the standard condition seems to be firing.
When we backtrack looking for IN_M_STAG_EXP_TNAME, we see that it’s entered only when all the other strings that can follow a “<” haven’t been recognized. We need to match the “<” in the default state. So instead of looking for “?” after a “<” has been recognized, we need to look for the full sequence “<?”.
state IN_M_DEFAULT: /<\?python\b/ : paint(include, TPL_OPERATOR), => IN_SSL_DEFAULT
recompile, repackage, reinstall, and reload….
Now strings and numeric constants are colored differently in the python block, but the “def” string is colored the same as operators. I brought up Preferences|Fonts and Colors|Lang-Specific|Kid, and gave identifiers, keywords, and operators all different, garish colors. After saving, I see that none of them are recognized in all three types of Python code blocks: the PIs, ${...} strings, and “py:” attribute values. The problem is most likely in the pythonlex.udl file, so I’ll have a look at that.
The first mistake was here:
state IN_SSL_IDENTIFIER_1: '.' : paint(upto, SSL_IDENTIFIER), paint(include, SSL_OPERATOR) /[^$NMCHAR]/ : paint(upto, SSL_OPERATOR), redo, => IN_SSL_DEFAULT
Since periods are colored with the paint/include action, I got the second action wrong. It should be
/[^$NMCHAR]/ : paint(upto, SSL_IDENTIFIER), redo, => IN_SSL_DEFAULT
If this is the fix, it should handle keywords as well. The keywords declaration listed all the words we want to be treated as keywords, and the keyword_style declaration specified that any time we finish a token of style SSL_IDENTIFIER that is in the keyword list, it should be recolored with style SSL_WORD. Let’s lather, rinse, and check once again…
And it worked. Now we can test the various boundaries of our spec.
The Mandelbrot sample has a few py:content attributes, using double-quoted strings. We can insert a single-quoted string inside a double-quoted py:content attribute string. Escaping single-quotes work, and triple-single-quoted strings work too. Note that we can’t escape double-quotes inside these strings, because they’re first parsed by the XML parser, which doesn’t know about backslashes. If you really need a double-quote inside one of these strings, you need to specify it as “"”, and Python will see a ‘”‘.
However, single-quoted strings aren’t working as well. I get lexing in them, but as soon as I enter a double-quote, I only seem to get sequences of string and default styles, until the closing single-quote. Back to the code…
state IN_SSL_DSTRING /\\[\r\n]/ : => IN_SSL_DSTRING_LINECONT /\\./ : # "" /$/ : paint(upto, SSL_STRING), => IN_SSL_DEFAULT # No EOLString in UDL "'" : paint(upto, SSL_STRING), => IN_SSL_DEFAULT
Another typo. The “D” in “DSTRING” indicates a double-quote, but I’m ending the string with a single-quote. The last condition should be:
'"' : paint(upto, SSL_STRING), => IN_SSL_DEFAULT
Remember the four “REs”… You did write a shell script or batch file for compiling and packaging, right? Unfortunately you can’t pass a XPI to Komodo on the command-line. On Windows I keep a file manager handy to drag-and-drop the XPI’s icon on Komodo. You can also add an “Open-File Shortcut” to your toolbox pointing to the directory containing the XPI. And one more time-saver, if you prefer running Komodo from the command-line rather than from an icon, is that closing Komodo automatically closes the Installer box as well.
So we now have working Python blocks, Python-content attributes, and embedded ${...} strings. Working through our test suite from Section 2.2 Test Planning, we see that ${...} isn’t working in text content.
The problem is obviously in html2python.udl, because we’re failing to transition from HTML to Python. And sure enough, I forgot to copy the rules for that from this document to the code file.
Another cycle, everything that was working before is still working (the advantage of testing lexers is you can look at the screen, but this is also one of the big disadvantages. Batch tests with scripts would be a great asset here).
Continuing down the list from where we left off, we try the following tests, verifying that ${...} sequences are either recognized as Python transition strings, or ignored, depending on the context:
We have no feedback on why that last test-cas failed, and need to dig a bit deeper.
This is where there’s an advantage in running Komodo from the command-line with the -v option. This is the feature that was implemented with that more complex pattern variable near the top of html2python.udl. It turns out that when we launch Komodo, it emits three error messages to the console with -v on:
udl: failed to compile ptn <(?&^|[^\w_\$])\$(?=[\w_])>: failed at offset 3 (^|[^\w_\$])\$(?=[\w_])): unrecognized character after (?< udl: failed to compile ptn <(?&^|[^\w_\$])\$(?=[\w_])>: failed at offset 3 (^|[^\w_\$])\$(?=[\w_])): unrecognized character after (?< udl: failed to compile ptn <(?&^|[^\w_\$])\$(?=[\w_])>: failed at offset 3 (^|[^\w_\$])\$(?=[\w_])): unrecognized character after (?<
Seeing this message three times makes sense, since we use that pattern three times. Let’s fire up the RxToolkit (assuming you’re using Komodo IDE or the old 3.5 version), and see what it says…
That didn’t take long. The “<” after “(?” is highlighted, and there’s a hard-to-miss error message complaining about the regex. I wanted to match dollar-signs that are either at the start of the line, or are not preceded by an identifier or other dollar sign. I forgot to put an “=” after the “<“, so let’s try that.
That gives a new error message: “look-behind requires a fixed-width pattern”. OK, I don’t need to put the ^ anchor in a look-behind, so let’s rewrite the pattern like so:
(?:^|(?<=[^\w_\$]))\$(?=[\w_])
The error message is gone. Now put these sample strings in the Text box, and see which ones match (be sure the “Match All” button is selected in the top row):
$foo $foo abc$foo abc $foo abc $12.34 abc*$foo for i in $*
Test #6 failed — obviously we don’t want to interpret a price as a reference to a Python object. I fixed this by changing the occurrence of “\w” after the “$” to a stricter “a-zA-Z”. If you’re following with the Rx Toolkit, you’ll see that the line containing “abc $12.34” is no longer highlighted, and no other lines of the sample text were affected.
So we set the pattern variable PY_HTML_DOLLAR_START to '(?:^|(?<=[^\w_\$]))\$(?=[a-zA-Z_])', and cycle yet again. And see that while the “$” characters are now colored as identifiers, the following characters aren’t. This is the case in all three contexts: text content, single-quoted plain attribute strings, and double-quoted strings.
And it was yet another typo:
state IN_M_PYTHON_UNBRACKETED_EXPN: '.' : paint(upto, SSL_IDENTIFIER), paint(include, SSL_OPERATOR) /[^\W]/: paint(upto, SSL_IDENTIFIER), redo, spop_check => IN_M_DEFAULT
the second pattern is a double-negative. It should be /[\W]/
That fixed that one. and we find the other tests for recognizing identifier shortcuts work.
So we’ve done static checking of all the Kid transition strings. We also fiddle with the Komodo editor contents to make sure that changes are updated quickly and correctly. If you implement a language and notice an anomaly, it’s most likely a bug in UDL that we’ve made, not something you need to fix.
We also want to make sure code-completion and auto-indent are working reasonably well. But all along we’ve noticed that there’s no code-completion going on with HTML tags. It turns out that there’s no completion in the other sections either. The next section will explain why, and show how to add them.
3. Auto-Indenting and Code-Completion
“Smart” auto-indenting and code-folding appear to be working correctly in HTML. Pressing return after a “{” in the JS and CSS modes correctly increases the indentation, and typing a “}” at the start of the line shifts the close-brace to the previous indentation level. All good. The folding looks right as well.
The Python section is a bit different. There is no folding based on indentation levels, like there is in the .py files inside Komodo. This is because code-folding is done by the scintilla components, and Luddite does not yet have a way of expressing fold levels based on indentation levels. However the auto-indentation should be working, and it isn’t. When we press return after “def color(x,y):”, Komodo should automatically increase the indent level by one, and it fails to.
Like any debugging scenario, there are two places to look more closely: the symptom, and the cause. The symptom, in this case, is failure to do Python-style auto-indenting. Let’s have a closer look at the buffer. It seems fine, maybe too fine. Remember when I created a garish color scheme for my Kid documents? I had decided to assign operators a hard-to-miss, hard-to-look-at crimson. The operators made the HTML, JavaScript, and CSS sections of the code hard to look at, but the part of my brain that was looking for missing styles was fooled by the part that liked the calmer Python section. A closer look showed that operators weren’t getting recognized in the Python section. Auto-indenting in Python mode depends on distinguishing characters like “:” in an operator context from “:”s appearing elsewhere.
So let’s look back at the source code. We’ll fire up the Rx Toolkit, specify the pattern we’re using to recognize operator characterrs in the pattern field, and put the “def color” line in the subject field.
We’ll have to manually expand the pattern “[$OP]” to give [~!@%^&*()-=+[]{}\\|;:,.<>/?], and we’re told that there are no matches. At least it’s consistent with the behavior we see in the editor, so we’ll have to look more closely at the regular expression to find the cause of the problem.
While I was writing this regex, I kept in mind the relaxed requirements for escaping special characters inside square brackets. In fact, the only characters that need escaping are the backslash itself, and the right-square bracket character (“]”). Once I looked at it, I could see it wasn’t escaped. The pattern I had written was matching one character in ~!@%^&*()-=+[, followed by the sequence {}\\|;:,.<>>/?]. By putting a backslash before the inner ‘]’, the Rx Toolkit tells me they match. So let’s change the pattern definition from
pattern OP = '~!@%^&*()-=+[]{}\\|;:,.<>/?'
to
pattern OP = '~!@%^&*()-=+[\]{}\\|;:,.<>/?'
and cycle. Auto-indentation is now *partly* working. Pressing return after a “:” doesn’t advance indentation, but pressing return on a line that starts with a “dedenting” keyword like “return” or “break” decreases it. It looks like an internal bug in Komodo…. Yes. You can read more at. Until this bug is fixed, “:” handling won’t work in Python segments of Kid files.
As for code-completion, at this point UDL doesn’t help us generate the required files, and Komodo isn’t yet doing code-completion for Python in multi-language documents.
If you’re feeling adventurous, you could copy a file like lang_mason.py out of komodo-install/lib/mozilla/python/komodo/codeintel2, call it “lang_kid.py“, change all occurrences of “Mason” to “Kid” and occurrences of “Perl” to “Python” (leaving the shebang line alone), make sure there are no syntax errors in lang_kid.py, copy it back to the Komodo codeintel2 directory, and restart Komodo. If Komodo fails to start, or starts up, but without any loaded buffers, you could either consult the pystderr.log and pystdout.log files in your application data area, or run Komodo from the command-line with the -v option, to better see error messages as they are triggered.
At this point you should find code-completion working for HTML and CSS in style tags. We haven’t implemented the class for multi-language Python code-completion yet, and when we do, JavaScript completion will fall out of it. When we ship that version of Komodo, the version of the Kid lexer you build today should inherit the new functionality in the new version, not even requiring a recompile.
Appendix A. Style Names
The first section consists of markup names. Some are a bit cryptic. The “S” in “STAG” stands for “start”; the “E” in “ETAG” stands for “end”; the “C” in “TAGC” stands for “close”, and the “O” in “TAGO” stands for “open”. “EMP” stands for “EMPTY”. The other markup terms should be self-evident in this angle-bracket-inundated world.
SCE_UDL_M_DEFAULT SCE_UDL_M_STAGO SCE_UDL_M_TAGNAME SCE_UDL_M_TAGSPACE SCE_UDL_M_ATTRNAME SCE_UDL_M_OPERATOR SCE_UDL_M_STAGC SCE_UDL_M_EMP_TAGC SCE_UDL_M_STRING SCE_UDL_M_ETAGO SCE_UDL_M_ETAGC SCE_UDL_M_ENTITY SCE_UDL_M_PI SCE_UDL_M_CDATA SCE_UDL_M_COMMENT
SCE_UDL_CSS_DEFAULT
SCE_UDL_CSS_COMMENT
SCE_UDL_CSS_NUMBER
SCE_UDL_CSS_STRING
SCE_UDL_CSS_WORD
SCE_UDL_CSS_IDENTIFIER
SCE_UDL_CSS_OPERATOR
SCE_UDL_CSL_DEFAULT
SCE_UDL_CSL_COMMENT
SCE_UDL_CSL_COMMENTBLOCK
SCE_UDL_CSL_NUMBER
SCE_UDL_CSL_STRING
SCE_UDL_CSL_WORD
SCE_UDL_CSL_IDENTIFIER
SCE_UDL_CSL_OPERATOR
SCE_UDL_CSL_REGEX
SCE_UDL_SSL_DEFAULT
SCE_UDL_SSL_COMMENT
SCE_UDL_SSL_COMMENTBLOCK
SCE_UDL_SSL_NUMBER
SCE_UDL_SSL_STRING
SCE_UDL_SSL_WORD
SCE_UDL_SSL_IDENTIFIER
SCE_UDL_SSL_OPERATOR
SCE_UDL_SSL_REGEX
SCE_UDL_SSL_VARIABLE
SCE_UDL_TPL_DEFAULT
SCE_UDL_TPL_COMMENT
SCE_UDL_TPL_COMMENTBLOCK
SCE_UDL_TPL_NUMBER
SCE_UDL_TPL_STRING
SCE_UDL_TPL_WORD
SCE_UDL_TPL_IDENTIFIER
SCE_UDL_TPL_OPERATOR
SCE_UDL_TPL_VARIABLE
References
1. While I was writing this I saw a request in a Rails-related feed asking if anyone was using Liquid templates. A quick google search for “liquid” came up with about 12 billion hits, which shows you just how quickly this template language thing is being picked up.
2. “kid.org” was taken by Kennewick Irrigation District; now you don’t have to look it up
3. If you open a .udl file in Komodo, you’ll see syntax-coloring for the different parts. See how it’s done in luddite.udl.
4. While you’re opening files in Komodo, you might want to open the Luddite documentation in the help section. The overview is in the “Komodo Reference” under “User-Defined Languages”, and the language reference is at “Luddite Reference”.
Title image courtesy of Willi Heidelbach on Pixabay. | https://www.activestate.com/blog/adding-new-languages-komodo-udl/ | CC-MAIN-2022-05 | refinedweb | 9,088 | 56.05 |
Hey,
New psychopy3 user here in need of some help.
I am trying to randomize the pairing of two stimuli images that flash on the screen at the same time for a total of 60 trials. Within these 60 trials I need to fulfill these 3 cases:
- a cupcake on the left and a muffin on the right 15 times
- a muffin on the left and a cupcake on the right 15 times
- a cupcake on the left and a cupcake on the right 30 times
I have both 8 cupcake images and 8 muffin images (excel file below) that need to be randomly paired together to meet these 3 criteria:
At the very beginning of the experiment I’ve set up a routine with some code that does the following:
import random, xlrd random.seed() in_file = 'cupmuf_database.xlsx' num_items = 8 num_tests = 60 cur = 0
After some instructions for participants comes my trial routine.
In begin routine:
inbook = xlrd.open_workbook(in_file) insheet = inbook.sheet_by_index(0) cases = ["c_cupR_mufL","c_mufR_cupL","c_cupL_cupR"] cup_stim = [] muf_stim = [] c_cupR_mufL_count = 15 c_mufR_cupL_count = 15 c_cupL_cupR_count = 30 left = [] right = [] correct=[] for rowx in range(1,num_items+1): row = insheet.row_values(rowx) cup_stim.append(row[0]) muf_stim.append(row[1]) for x in range(60): if (c_cupR_mufL_count == 0 and "c_cupR_mufL" in cases): cases.remove("c_cupR_mufL") if (c_mufR_cupL_count == 0 and "c_mufR_cupL" in cases): cases.remove("c_mufR_cupL") if (c_cupL_cupR_count == 0 and "c_cupL_cupR" in cases): cases.remove("c_cupL_cupR") ran = random.randrange(0, len(cases)) test = cases[ran] if (test == "c_cupR_mufL"): right.append(cup_stim[random.randrange(1, 8)]) left.append(muf_stim[random.randrange(1, 8)]) c_cupR_mufL_count = c_cupR_mufL_count - 1 correct.append(1) if (test == "c_mufR_cupL"): left.append(cup_stim[random.randrange(1, 8)]) right.append(muf_stim[random.randrange(1, 8)]) c_mufR_cupL_count = c_mufR_cupL_count - 1 correct.append(1) if (test == "c_cupL_cupR"): leftVal = random.randrange(1, 8) rightVal = random.randrange(1, 8) if leftVal == rightVal: if rightVal == 8: rightVal = rightVal - 1 else: rightVal = rightVal + 1 left.append(cup_stim[leftVal -1]) right.append(cup_stim[rightVal -1]) c_cupL_cupR_count = c_cupL_cupR_count - 1 correct.append(0)
In end routine:
thisExp.addData('left', left[cur]) thisExp.addData('right', right[cur]) thisExp.addData('correct', correct[cur]) if key_resp_2.keys == "left" and correct[cur] == 1: thisExp.addData('res', 1) else: thisExp.addData('res', 0) if left[cur] == muf_stim or right[cur] == muf_stim: isTarget = 1 else: isTarget = 0 cur = cur + 1
My loop is set for nReps to equal $num_tests (which I’ve defined as 60).
When I run this I do get 60 trials each time and all 8 cupcake and muffin images are being used but I don’t get the correct number of pairings for each of my 3 cases. For example, I’ll get 23 cupcake left and cupcake right instead of 30 cupcake left and cupcake right.
I hope this was enough information, I can clarify if something doesn’t make sense.
Thanks in advance. | https://discourse.psychopy.org/t/counters-to-randomize-stimuli-images-not-working-properly/14444 | CC-MAIN-2021-43 | refinedweb | 471 | 51.55 |
Shifting variables in a circular fashion
This content was COPIED from BrainMass.com - View the original, and get the already-completed solution here!
Please help with the following problem.
This needs to be in "C"
Write a function that shifts the stored value of five character variables in a circular fashion. Your function should work in the following way. Suspose that C1, C2, C3, C4, C5 are variables of type char, and suspose that the values of these variables are 'A', 'B', 'C', 'D', 'E', respectively.
The function call shift(&c1,&c2,&c3,&c4,&c5) should cause the variables C1, C2, C3, C4, C5 to have the values 'B', 'C', 'D', 'E', 'A', respectively.
The function definition starts as follows:
void shift(char *p1, char *p2, char *p3, char *p4, char *p5)
{
Test the function by calling it five times and printing out, in turn, BCDEA, CDEAB, DEABC, EABCD, and ABCDE.
****This needs to be in "C"*****© BrainMass Inc. brainmass.com March 4, 2021, 8:19 pm ad1c9bdddf
Solution Preview
#include <stdio.h>
static void shift(char *p1, char *p2, char *p3, char *p4, char *p5);
int main()
{
char C1, C2, C3, C4, C5 ;
int i ...
Solution Summary
This solution helps with shifting variables in a circular fashion. Step by step codes are provided in the solution. | https://brainmass.com/computer-science/c/shifting-variables-circular-fashion-160011 | CC-MAIN-2021-17 | refinedweb | 217 | 72.36 |
Algorithm Implementation/Sorting/Schwartzian transform
Perl[edit]
Perl's compact list-manipulation functions can perform the entire transform in a single statement, although it must be written backwards:
@sorted_array = map { $_->[0] } # extract original list elements sort { $a->[1] <=> $b->[1] } # sort list by keys map { [$_, -M $_] } # pair up list elements with keys @files_array;
This is a complete Schwartzian Transform, showing a multi-stage sort based on memoized keys of size and modtime.
my @sorted_files = map $_->[0], # extract original name sort { $a->[1] <=> $b->[1] # sort first numerically by size (smallest first) or $b->[2] <=> $a->[2] # then numerically descending by modtime age (oldest first) or $a->[0] cmp $b->[0] # then stringwise by original name } map [$_, -s $_, -M $_], # compute tuples of name, size, modtime glob "*"; # of all files in the directory
Python[edit]
Python programmers use the transform in sorts where the comparison operation may be expensive.
In this example, f(x) returns a key which is suitable for using for sorting. For instance, it might return the length of x, or it might do a database lookup based on the value of x.
# python2.4 new_list = sorted(old_list, key=f)
The key function can return a tuple of values if secondary and further sort keys are desired, taking advantage of the fact that tuples are ordered first by the first key, and then by the second key if the first ties, etc. If the default sort for the keys is not enough, a comparator function can be given with an additional keyword argument cmp, for example:
# python2.4; removed in python3.0 new_list = sorted(old_list, key=f, cmp=lambda a,b:cmp(a[0],b[0]) or cmp(b[1],a[1]))
Note that the key function f should do the expensive work as it's called only once for each key whereas the comparator function is called each time the sort algorithm has to compare two elements. A comparator function can no longer be used in Python 3.0; only a key. The function sorted is new in Python 2.4, before that only method sort was available and more than one statement was required. The key function is also new in Python 2.4 so in Python 2.3 one had to spell out the transform in a way similar to the following, taking advantage of the fact that the first element of a tuple will be used for comparison first:
# python2.3 new_list = [(f(x), x) for x in old_list] new_list.sort() new_list = [x[1] for x in new_list]
If desired, a comparator function can be given to the sort here as well (Python 2.4; removed in Python 3.0).
The following is a version that is similar to the Perl idiom (except for the extra parentheses at the end), again taking advantage of sorting of tuples by putting the function results first:
new_list = map(lambda x: x[1], sorted( map(lambda x: (f(x), x), old_list)))
The
zip built-in can be used instead of the inline lambda function giving:
new_list = zip(* sorted( zip(map(f, old_list), old_list)))[1]
Ruby[edit]
Ruby programmers have their own shortcut.
new_list = old_list.sort_by {|file| file.mtime }
However, this is not the full Schwartzian Transform, because the comparison of the memoized keys is fixed. (Though there is a trick for getting around that.)
Full Schwartzian Transform[edit]
A true Schwartzian Transform also spells out how the various memoized keys are compared (as strings, as numbers) including lazy logic that can avoid comparisons in secondary and tertiary keys if distinction in the primary keys suffice.
sorted_files = Dir["*"]. # Get all files collect{|f| [f, test(?s, f), test(?M, f)]}. # compute tuples of name, size, modtime sort {|a, b| # sort a[1] <=> b[1] or # -- by increasing size b[2] <=> a[2] or # -- by age descending a[0] <=> b[0] # -- by name }.collect{|a| a[0]} # extract original name
Note that since collect, sort, etc. are all method calls, that the actions read forwards, rather than backwards as in the original Perl.
And now for the trick to make the shortcut method do everything that the full transform can. The trick is that in Ruby objects know how to sort themselves, and arrays sort lexicographically (i.e. by comparing the first value, then second value, etc.). This means that you can construct values that will sort themselves by fairly complex logic.
# Here is the helper class. class InReverse include Comparable attr :value def initialize (value) @value = value end def <=> (other) other.value <=> @value end end # And now we can do the complex transform using sort_by. sorted_files = Dir["*"].sort_by{|f| [test(?s, f), InReverse.new(test(?M, f)), f]}
Haskell[edit]
This is the idiomatic Haskell way of comparing by a transformed version of the elements:
import Data.List (sortBy) import Data.Ord (comparing) sortOn f = sortBy (comparing f)
Here the "comparing" function takes a function and returns a comparison function based on comparing the results of the function application. It is defined like this:
comparing f x y = compare (f x) (f y)
Here is a version that identically mimicks the traditional Perl idiom:
import Data.List (sortBy) import Data.Ord (comparing) sortOn' f = map fst . sortBy (comparing snd) . map (\x -> (x, f x))
However, we can take advantage of the fact that tuples are first ordered by their first element, then second, etc., by putting the function results as the first element, and then using the default comparator:
import Data.List (sort) sortOn'' f = map snd . sort . map (\x -> (f x, x))
Since the tuple compare requires both element types to be instances of Ord, however, this last implementation has a subtly different type:
sortOn, sortOn' :: (Ord b) => (a -> b) -> [a] -> [a] sortOn'' :: (Ord a, Ord b) => (a -> b) -> [a] -> [a]
OCaml[edit]
This is probably the easiest way to do it in OCaml:
let comparing f x y = compare (f x) (f y) let newList = List.sort (comparing f) oldList
Here is a version that identically mimicks the traditional Perl idiom (except for the extra parentheses):
let comparing f x y = compare (f x) (f y) let newList = List.map fst ( List.sort (comparing snd) ( List.map (fun x -> x, f x) oldList))
However, we can take advantage of the fact that tuples are first ordered by their first element, then second, etc., by putting the function results as the first element, and then using the default comparator:
let newList = List.map snd ( List.sort compare ( List.map (fun x -> f x, x) oldList))
Javascript[edit]
In modern versions of Javascript (Firefox 1.5, Internet Explorer 9, Opera 9.6, Chrome, Safari 3, etc.; standardized in ECMAScript edition 5), arrays have a map function in their prototype, allowing one to easily write a Schwartzian transform:
function sortOn(arr, fun) { return arr.map(function (x) { return [ x, fun(x) ]; }).sort(function (a, b) { // If fun(a) always returns a number, this can be replaced by: return a[1] - b[1]; return a[1] < b[1] ? -1 : a[1] > b[1] ? 1 : 0; }).map(function (x) { return x[0]; }); }
Example usage:
js> print(sortOn([ 'Charlie', 'alice', 'BOB' ], function (s) { return s.toUpperCase(); })); alice,BOB,Charlie
For older browsers, a compatibility map prototype function can be used. | https://en.wikibooks.org/wiki/Algorithm_Implementation/Sorting/Schwartzian_transform | CC-MAIN-2016-26 | refinedweb | 1,213 | 62.17 |
mow.cli alternatives and similar packages
Based on the "Standard CLI" category
cobra9.9 7.1 mow.cli VS cobraA Commander for modern Go CLI interactions
urfave/cli9.8 9.3 mow.cli VS urfave/cliA small package for building command line apps in Go.
kingpin8.9 5.4 mow.cli VS kingpinA command line and flag parser supporting sub commands.
The Platinum Searcher8.8 0.0 mow.cli VS The Platinum SearcherA code search tool similar to ack and the_silver_searcher(ag). It supports multi platforms and multi encodings.
go-flags8.4 0.0 mow.cli VS go-flagsgo command line option parser
Dnote8.3 8.3 mow.cli VS DnoteA simple and end-to-end encrypted notebook for developers.
readline8.3 0.0 mow.cli VS readlineA pure golang implementation that provide most of features in GNU-Readline under MIT license.
pflag8.1 3.2 mow.cli VS pflagDrop-in replacement for Go's flag package, implementing POSIX/GNU-style --flags.
docopt.go7.9 0.0 mow.cli VS docopt.goA command-line arguments parser that will make you smile.
mitchellh/cli7.7 2.8 mow.cli VS mitchellh/cliA Go library for implementing command-line interfaces.
cli-init7.5 0.0 mow.cli VS cli-initThe easy way to start building Golang command line application.
liner7.3 0.9 mow.cli VS linerA Go readline-like library for command-line interfaces.
complete7.1 3.2 mow.cli VS completeWrite bash completions in Go + Go command bash completion.
flaggy7.0 6.2 mow.cli VS flaggyA robust and idiomatic flags package with excellent subcommand support.
cli6.9 1.6 mow.cli VS cliA feature-rich and easy to use command-line package based on golang tag
ops6.5 7.6 mow.cli VS opsUnikernel Builder/Orchestrator.
argparse5.6 6.0 mow.cli VS argparseCommand line argument parser inspired by Python's argparse module.
climax5.4 0.0 mow.cli VS climaxAn alternative CLI with "human face", in spirit of Go command
sflags4.7 0.3 mow.cli VS sflagsStruct based flags generator for flag, urfave/cli, pflag, cobra, kingpin and other libraries.
commandeer4.6 3.9 mow.cli VS commandeerDev-friendly CLI apps: sets up flags, defaults, and usage based on struct fields and tags.
wmenu4.6 2.8 mow.cli VS wmenuAn easy to use menu structure for cli applications that prompts users to make choices.
flag4.4 4.4 mow.cli VS flagA simple but powerful command line option parsing library for Go support subcommand
1build4.4 7.5 mow.cli VS 1buildCommand line tool to frictionlessly manage project-specific commands.
ukautz/clif4.4 0.0 mow.cli VS ukautz/clifA small command line interface framework.
job3.7 4.4 mow.cli VS jobJOB, make your short-term command as a long-term job.
calories3.3 0.0 mow.cli VS caloriesCalories Tracker for the Commandline
gocmd3.1 0.0 mow.cli VS gocmdGo library for building command line applications.
wlog3.0 1.9 mow.cli VS wlogA simple logging interface that supports cross-platform color and concurrency.
clîr2.9 6.4 mow.cli VS clîrA Simple and Clear CLI library. Dependency free.
cmdr2.9 9.5 mow.cli VS cmdrA POSIX/GNU style, getopt-like command-line UI Go library.
strumt2.8 3.9 mow.cli VS strumtLibrary to create prompt chain.
flagvar2.6 2.5 mow.cli VS flagvarA collection of flag argument types for Go's standard flag package.
go-getoptions2.2 7.1 mow.cli VS go-getoptionsGo option parser inspired on the flexibility of Perl’s GetOpt::Long.
go-commander2.0 1.1 mow.cli VS go-commanderGo library to simplify CLI workflow.
go-cli1.8 4.1 mow.cli VS go-cliA full-featured and easy to use command-line package
argv1.5 2.7 mow.cli VS argvA Go library to split command line string as arguments array using the bash syntax.
sand1.3 0.0 mow.cli VS sandSimple API for creating interpreters and so much more.
ts1.0 1.6 mow.cli VS tsTimestamp convert & compare tool.
Go-Console0.4 7.5 mow.cli VS Go-ConsoleGoConsole allows you to create butifull command-line commands with arguments and options. (follow the docopt standard)
multi-tailf0.3 0.0 mow.cli VS multi-tailfwatch multiple logs on local or remote servers.
hiboot cli0.2 - mow.cli VS hiboot clicli application framework with auto configuration and dependency injection.
Do you think we are missing an alternative of mow.cli or a related project?
Popular Comparisons
README
mow.cli
Package cli provides a framework to build command line applications in Go with most of the burden of arguments parsing and validation placed on the framework instead of the user.
Getting Started
The following examples demonstrate basic usage the package.
Simple Application
In this simple application, we mimic the argument parsing of the standard UNIX cp command. Our application requires the user to specify one or more source files followed by a destination. An optional recursive flag may be provided.
package main import ( "fmt" "os" "github.com/jawher/mow.cli" ) func main() { // create an app app := cli.App("cp", "Copy files around") //" var ( // declare the -r flag as a boolean flag recursive = app.BoolOpt("r recursive", false, "Copy files recursively") // declare the SRC argument as a multi-string argument src = app.StringsArg("SRC", nil, "Source files to copy") // declare the DST argument as a single string (string slice) arguments dst = app.StringArg("DST", "", "Destination where to copy files to") ) // Specify the action to execute when the app is invoked correctly app.Action = func() { fmt.Printf("Copying %v to %s [recursively: %v]\n", *src, *dst, *recursive) } // Invoke the app passing in os.Args app.Run(os.Args) }
Pointers to existing variables
This variant of the cp command uses the Ptr variants, where you can pass pointers to existing variables instead of declaring new ones for the options/arguments:
package main import ( "fmt" "os" cli "github.com/jawher/mow.cli" ) type Config struct { Recursive bool Src []string Dst string } func main() { var ( app = cli.App("cp", "Copy files around") cfg Config ) //" // declare the -r flag as a boolean flag app.BoolOptPtr(&cfg.Recursive, "r recursive", false, "Copy files recursively") // declare the SRC argument as a multi-string argument app.StringsArgPtr(&cfg.Src, "SRC", nil, "Source files to copy") // declare the DST argument as a single string (string slice) arguments app.StringArgPtr(&cfg.Dst, "DST", "", "Destination where to copy files to") // Specify the action to execute when the app is invoked correctly app.Action = func() { fmt.Printf("Copying using config: %+v\n", cfg) } // Invoke the app passing in os.Args app.Run(os.Args) }
Multi-Command Application
In the next example, we create a multi-command application in the same style as familiar commands such as git and docker. We build a fictional utility called uman to manage users in a system. It provides two commands that can be invoked: list and get. The list command takes an optional flag to specify all users including disabled ones. The get command requires one argument, the user ID, and takes an optional flag to specify a detailed listing.
package main import ( "fmt" "os" "github.com/jawher/mow.cli" ) func main() { app := cli.App("uman", "User Manager") app.Spec = "[-v]" var ( verbose = app.BoolOpt("v verbose", false, "Verbose debug mode") ) app.Before = func() { if *verbose { // Here we can enable debug output in our logger for example fmt.Println("Verbose mode enabled") } } // Declare our first command, which is invocable with "uman list" app.Command("list", "list the users", func(cmd *cli.Cmd) { // These are the command-specific options and args, nicely scoped // inside a func so they don't pollute the namespace var ( all = cmd.BoolOpt("all", false, "List all users, including disabled") ) // Run this function when the command is invoked cmd.Action = func() { // Inside the action, and only inside, we can safely access the // values of the options and arguments fmt.Printf("user list (including disabled ones: %v)\n", *all) } }) // Declare our second command, which is invocable with "uman get" app.Command("get", "get a user details", func(cmd *cli.Cmd) { var ( detailed = cmd.BoolOpt("detailed", false, "Disaply detailed info") id = cmd.StringArg("ID", "", "The user id to display") ) cmd.Action = func() { fmt.Printf("user %q details (detailed mode: %v)\n", *id, *detailed) } }) // With the app configured, execute it, passing in the os.Args array app.Run(os.Args) }
A Larger Multi-Command Example
This example shows an alternate way of organizing our code when dealing with a larger number of commands and subcommands. This layout emphasizes the command structure and defers the details of each command to subsequent functions. Like the prior examples, options and arguments are still scoped to their respective functions and don't pollute the global namespace.
package main import ( "fmt" "os" "github.com/jawher/mow.cli" ) // Global options available to any of the commands var filename *string func main() { app := cli.App("vault", "Password Keeper") // Define our top-level global options filename = app.StringOpt("f file", os.Getenv("HOME")+"/.safe", "Path to safe") // Define our command structure for usage like this: app.Command("list", "list accounts", cmdList) app.Command("creds", "display account credentials", cmdCreds) app.Command("config", "manage accounts", func(config *cli.Cmd) { config.Command("list", "list accounts", cmdList) config.Command("add", "add an account", cmdAdd) config.Command("remove", "remove an account(s)", cmdRemove) }) app.Run(os.Args) } // Sample use: vault list OR vault config list func cmdList(cmd *cli.Cmd) { cmd.Action = func() { fmt.Printf("list the contents of the safe here") } } // Sample use: vault creds reddit.com func cmdCreds(cmd *cli.Cmd) { cmd.Spec = "ACCOUNT" account := cmd.StringArg("ACCOUNT", "", "Name of account") cmd.Action = func() { fmt.Printf("display account info for %s\n", *account) } } // Sample use: vault config add reddit.com -u username -p password func cmdAdd(cmd *cli.Cmd) { cmd.Spec = "ACCOUNT [ -u=<username> ] [ -p=<password> ]" var ( account = cmd.StringArg("ACCOUNT", "", "Account name") username = cmd.StringOpt("u username", "admin", "Account username") password = cmd.StringOpt("p password", "admin", "Account password") ) cmd.Action = func() { fmt.Printf("Adding account %s:%s@%s", *username, *password, *account) } } // Sample use: vault config remove reddit.com twitter.com func cmdRemove(cmd *cli.Cmd) { cmd.Spec = "ACCOUNT..." var ( accounts = cmd.StringsArg("ACCOUNT", nil, "Account names to remove") ) cmd.Action = func() { fmt.Printf("Deleting accounts: %v", *accounts) } }
Comparison to Other Tools
There are several tools in the Go ecosystem to facilitate the creation of command line tools. The following is a comparison to the built-in flag package as well as the popular urfave/cli (formerly known as codegangsta/cli):
Unlike the simple packages above, docopt is another library that supports rich set of flag and argument validation. It does, however, fall short for many use cases including:
Installation
To install this package, run the following:
go get github.com/jawher/mow.cli
Package Documentation
<!-- Do NOT edit past here. This is replaced by the contents of the package documentation --> Package cli provides a framework to build command line applications in Go with most of the burden of arguments parsing and validation placed on the framework instead of the user.
Basics
To create a new application, initialize an app with cli.App. Specify a name and a brief description for the application:
cp := cli.App("cp", "Copy files around")
To attach code to execute when the app is launched, assign a function to the Action field:
cp.Action = func() { fmt.Printf("Hello world\n") }
To assign a version to the application, use Version method and specify the flags that will be used to invoke the version command:
cp.Version("v version", "cp 1.2.3")
Finally, in the main func, call Run passing in the arguments for parsing:
cp.Run(os.Args)
Options
To add one or more command line options (also known as flags), use one of the short-form StringOpt, StringsOpt, IntOpt, IntsOpt, Float64Opt, Floats64Opt, or BoolOpt methods on App (or Cmd if adding flags to a command or a subcommand). For example, to add a boolean flag to the cp command that specifies recursive mode, use the following:
recursive := cp.BoolOpt("R recursive", false, "recursively copy the src to dst")
or:
cp.BoolOptPtr(&cfg.recursive, "R recursive", false, "recursively copy the src to dst")
The first version returns a new pointer to a bool value which will be populated when the app is run, whereas the second version will populate a pointer to an existing variable you specify.
The option name(s) is a space separated list of names (without the dashes). The one letter names can then be called with a single dash (short option, -R), the others with two dashes (long options, --recursive).
You also specify the default value for the option if it is not supplied by the user.
The last parameter is the description to be shown in help messages.
There is also a second set of methods on App called String, Strings, Int, Ints, and Bool, which accept a long-form struct of the type: cli.StringOpt, cli.StringsOpt, cli.IntOpt, cli.IntsOpt, cli.Float64Opt, cli.Floats64Opt, cli.BoolOpt. The struct describes the option and allows the use of additional features not available in the short-form methods described above:
recursive = cp.Bool(cli.BoolOpt{ Name: "R recursive", Value: false, Desc: "copy src files recursively", EnvVar: "VAR_RECURSIVE", SetByUser: &recursiveSetByUser, })
Or:
recursive = cp.BoolPtr(&recursive, cli.BoolOpt{ Name: "R recursive", Value: false, Desc: "copy src files recursively", EnvVar: "VAR_RECURSIVE", SetByUser: &recursiveSet option option was explicitly set by the user or set via the default value.
You can only access the values stored in the pointers in the Action func, which is invoked after argument parsing has been completed. This precludes using the value of one option as the default value of another.
On the command line, the following syntaxes are supported when specifying options.
Boolean options:
-f single dash one letter name -f=false single dash one letter name, equal sign followed by true or false --force double dash for longer option names -it single dash for multiple one letter names (option folding), this is equivalent to: -i -t
String, int and float options:
-e=value single dash one letter name, equal sign, followed by the value -e value single dash one letter name, space followed by the value -Ivalue single dash one letter name, immediately followed by the value --extra=value double dash for longer option names, equal sign followed by the value --extra value double dash for longer option names, space followed by the value
Slice options (StringsOpt, IntsOpt, Floats64Opt) where option is repeated to accumulate values in a slice:
-e PATH:/bin -e PATH:/usr/bin resulting slice contains ["/bin", "/usr/bin"] -ePATH:/bin -ePATH:/usr/bin resulting slice contains ["/bin", "/usr/bin"] -e=PATH:/bin -e=PATH:/usr/bin resulting slice contains ["/bin", "/usr/bin"] --env PATH:/bin --env PATH:/usr/bin resulting slice contains ["/bin", "/usr/bin"] --env=PATH:/bin --env=PATH:/usr/bin resulting slice contains ["/bin", "/usr/bin"]
Arguments
To add one or more command line arguments (not prefixed by dashes), use one of the short-form StringArg, StringsArg, IntArg, IntsArg, Float64Arg, Floats64Arg, or BoolArg methods on App (or Cmd if adding arguments to a command or subcommand). For example, to add two string arguments to our cp command, use the following calls:
src := cp.StringArg("SRC", "", "the file to copy") dst := cp.StringArg("DST", "", "the destination")
Or:
cp.StringArgPtr(&src, "SRC", "", "the file to copy") cp.StringArgPtr(&dst, "DST", "", "the destination")
The first version returns a new pointer to a value which will be populated when the app is run, whereas the second version will populate a pointer to an existing variable you specify.
You then specify the argument as will be displayed in help messages. Argument names must be specified as all uppercase. The next parameter is the default value for the argument if it is not supplied. And the last is the description to be shown in help messages.
There is also a second set of methods on App called String, Strings, Int, Ints, Float64, Floats64 and Bool, which accept a long-form struct of the type: cli.StringArg, cli.StringsArg, cli.IntArg, cli.IntsArg, cli.BoolArg. The struct describes the arguments and allows the use of additional features not available in the short-form methods described above:
src = cp.Strings(StringsArg{ Name: "SRC", Desc: "The source files to copy", Value: "default value", EnvVar: "VAR1 VAR2", SetByUser: &srcSetByUser, })
Or:
src = cp.StringsPtr(&src, StringsArg{ Name: "SRC", Desc: "The source files to copy", Value: "default value", EnvVar: "VAR1 VAR2", SetByUser: &srcSet argument argument was explicitly set by the user or set via the default value.
You can only access the values stored in the pointers in the Action func, which is invoked after argument parsing has been completed. This precludes using the value of one argument as the default value of another.
Operators
The -- operator marks the end of command line options. Everything that follows will be treated as an argument, even if starts with a dash. For example, the standard POSIX touch command, which takes a filename as an argument (and possibly other options that we'll ignore here), could be defined as:
file := cp.StringArg("FILE", "", "the file to create")
If we try to create a file named "-f" via our touch command:
$ touch -f
It will fail because the -f will be parsed as an option, not as an argument. The fix is to insert -- after all flags have been specified, so the remaining arguments are parsed as arguments instead of options as follows:
$ touch -- -f
This ensures the -f is parsed as an argument instead of a flag named f.
Commands
This package supports nesting of commands and subcommands. Declare a top-level command by calling the Command func on the top-level App struct. For example, the following creates an application called docker that will have one command called run:
docker := cli.App("docker", "A self-sufficient runtime for linux containers") docker.Command("run", "Run a command in a new container", func(cmd *cli.Cmd) { // initialize the run command here })
The first argument is the name of the command the user will specify on the command line to invoke this command. The second argument is the description of the command shown in help messages. And, the last argument is a CmdInitializer, which is a function that receives a pointer to a Cmd struct representing the command.
Within this function, define the options and arguments for the command by calling the same methods as you would with top-level App struct (BoolOpt, StringArg, ...). To execute code when the command is invoked, assign a function to the Action field of the Cmd struct. Within that function, you can safely refer to the options and arguments as command line parsing will be completed at the time the function is invoked:
docker.Command("run", "Run a command in a new container", func(cmd *cli.Cmd) { var ( detached = cmd.BoolOpt("d detach", false, "Run container in background") memory = cmd.StringOpt("m memory", "", "Set memory limit") image = cmd.StringArg("IMAGE", "", "The image to run") ) cmd.Action = func() { if *detached { // do something } runContainer(*image, *detached, *memory) } })
Optionally, to provide a more extensive description of the command, assign a string to LongDesc, which is displayed when a user invokes --help. A LongDesc can be provided for Cmds as well as the top-level App:
cmd.LongDesc = `Run a command in a new container With the docker run command,.`
Subcommands can be added by calling Command on the Cmd struct. They can by defined to any depth if needed:
docker.Command("job", "actions on jobs", func(job *cli.Cmd) { job.Command("list", "list jobs", listJobs) job.Command("start", "start a new job", startJob) job.Command("log", "log commands", func(log *cli.Cmd) { log.Command("show", "show logs", showLog) log.Command("clear", "clear logs", clearLog) }) })
Command and subcommand aliases are also supported. To define one or more aliases, specify a space-separated list of strings to the first argument of Command:
job.Command("start run r", "start a new job", startJob)
With the command structure defined above, users can invoke the app in a variety of ways:
$ docker job list $ docker job start $ docker job run # using the alias we defined $ docker job r # using the alias we defined $ docker job log show $ docker job log clear
As a convenience, to assign an Action to a func with no arguments, use ActionCommand when defining the Command. For example, the following two statements are equivalent:
app.Command("list", "list all configs", cli.ActionCommand(list)) // Exactly the same as above, just more verbose app.Command("list", "list all configs", func(cmd *cli.Cmd)) { cmd.Action = func() { list() } }
Please note that options, arguments, specs, and long descriptions cannot be provided when using ActionCommand. This is intended for very simple command invocations that take no arguments.
Finally, as a side-note, it may seem a bit weird that this package uses a function to initialize a command instead of simply returning a command struct. The motivation behind this API decision is scoping: as with the standard flag package, adding an option or an argument returns a pointer to a value which will be populated when the app is run. Since you'll want to store these pointers in variables, and to avoid having dozens of them in the same scope (the main func for example or as global variables), this API was specifically tailored to take a func parameter (called CmdInitializer), which accepts the command struct. With this design, the command's specific variables are limited in scope to this function.
Interceptors
Interceptors, or hooks, can be defined to be executed before and after a command or when any of its subcommands are executed. For example, the following app defines multiple commands as well as a global flag which toggles verbosity:
app := cli.App("app", "bla bla") verbose := app.BoolOpt("verbose v", false, "Enable debug logs") app.Command("command1", "...", func(cmd *cli.Cmd) { if (*verbose) { logrus.SetLevel(logrus.DebugLevel) } }) app.Command("command2", "...", func(cmd *cli.Cmd) { if (*verbose) { logrus.SetLevel(logrus.DebugLevel) } })
Instead of duplicating the check for the verbose flag and setting the debug level in every command (and its sub-commands), a Before interceptor can be set on the top-level App instead:
app.Before = func() { if (*verbose) { logrus.SetLevel(logrus.DebugLevel) } }
Whenever a valid command is called by the user, all the Before interceptors defined on the app and the intermediate commands will be called, in order from the root to the leaf.
Similarly, to execute a hook after a command has been called, e.g. to cleanup resources allocated in Before interceptors, simply set the After field of the App struct or any other Command. After interceptors will be called, in order, from the leaf up to the root (the opposite order of the Before interceptors).
The following diagram shows when and in which order multiple Before and After interceptors are executed:
+------------+ success +------------+ success +----------------+ success | app.Before +---------------> cmd.Before +-------------> sub_cmd.Before +---------+ +------------+ +-+----------+ +--+-------------+ | | | +-v-------+ error | error | | sub_cmd | +-----------------------+ +-----------------------+ | Action | | | +-+-------+ +------v-----+ +-----v------+ +----------------+ | | app.After <---------------+ cmd.After <-------------+ sub_cmd.After <---------+ +------------+ always +------------+ always +----------------+ always
Exiting
To exit the application, use cli.Exit function, which accepts an exit code and exits the app with the provided code. It is important to use cli.Exit instead of os.Exit as the former ensures that all of the After interceptors are executed before exiting.
cli.Exit(1)
Spec Strings
An App or Command's invocation syntax can be customized using spec strings. This can be useful to indicate that an argument is optional or that two options are mutually exclusive. The spec string is one of the key differentiators between this package and other CLI packages as it allows the developer to express usage in a simple, familiar, yet concise grammar.
To define option and argument usage for the top-level App, assign a spec string to the App's Spec field:
cp := cli.App("cp", "Copy files around") cp.Spec = "[-R [-H | -L | -P]]"
Likewise, to define option and argument usage for a command or subcommand, assign a spec string to the Command's Spec field:
docker := cli.App("docker", "A self-sufficient runtime for linux containers") docker.Command("run", "Run a command in a new container", func(cmd *cli.Cmd) { cmd.Spec = "[-d|--rm] IMAGE [COMMAND [ARG...]]" : : }
The spec syntax is mostly based on the conventions used in POSIX command line applications (help messages and man pages). This syntax is described in full below. If a user invokes the app or command with the incorrect syntax, the app terminates with a help message showing the proper invocation. The remainder of this section describes the many features and capabilities of the spec string grammar.
Options can use both short and long option names in spec strings. In the example below, the option is mandatory and must be provided. Any options referenced in a spec string MUST be explicitly declared, otherwise this package will panic. I.e. for each item in the spec string, a corresponding *Opt or *Arg is required:
x.Spec = "-f" // or x.Spec = "--force" forceFlag := x.BoolOpt("f force", ...)
Arguments are specified with all-uppercased words. In the example below, both SRC and DST must be provided by the user (two arguments). Like options, any argument referenced in a spec string MUST be explicitly declared, otherwise this package will panic:
x.Spec="SRC DST" src := x.StringArg("SRC", ...) dst := x.StringArg("DST", ...)
With the exception of options, the order of the elements in a spec string is respected and enforced when command line arguments are parsed. In the example below, consecutive options (-f and -g) are parsed regardless of the order they are specified (both "-f=5 -g=6" and "-g=6 -f=5" are valid). Order between options and arguments is significant (-f and -g must appear before the SRC argument). The same holds true for arguments, where SRC must appear before DST:
x.Spec = "-f -g SRC -h DST" var ( factor = x.IntOpt("f", 1, "Fun factor (1-5)") games = x.IntOpt("g", 1, "# of games") health = x.IntOpt("h", 1, "# of hosts") src = x.StringArg("SRC", ...) dst = x.StringArg("DST", ...) )
Optionality of options and arguments is specified in a spec string by enclosing the item in square brackets []. If the user does not provide an optional value, the app will use the default value specified when the argument was defined. In the example below, if -x is not provided, heapSize will default to 1024:
x.Spec = "[-x]" heapSize := x.IntOpt("x", 1024, "Heap size in MB")
Choice between two or more items is specified in a spec string by separating each choice with the | operator. Choices are mutually exclusive. In the examples below, only a single choice can be provided by the user otherwise the app will terminate displaying a help message on proper usage:
x.Spec = "--rm | --daemon" x.Spec = "-H | -L | -P" x.Spec = "-t | DST"
Repetition of options and arguments is specified in a spec string with the ... postfix operator to mark an item as repeatable. Both options and arguments support repitition. In the example below, users may invoke the command with multiple -e options and multiple SRC arguments:
x.Spec = "-e... SRC..." // Allows parsing of the following shell command: // $ app -eeeee file1 file2 // $ app -e -e -e -e file1 file2
Grouping of options and arguments is specified in a spec string with parenthesis. When combined with the choice | and repetition ... operators, complex syntaxes can be created. The parenthesis in the example below indicate a repeatable sequence of a -e option followed by an argument, and that is mutually exclusive to a choice between -x and -y options.
x.Spec = "(-e COMMAND)... | (-x|-y)" // Allows parsing of the following shell command: // $ app -e show -e add // $ app -y // But not the following: // $ app -e show -x
Option groups, or option folding, are a shorthand method to declaring a choice between multiple options. I.e. any combination of the listed options in any order with at least one option selected. The following two statements are equivalent:
x.Spec = "-abcd" x.Spec = "(-a | -b | -c | -d)..."
Option groups are typically used in conjunction with optionality [] operators. I.e. any combination of the listed options in any order or none at all. The following two statements are equivalent:
x.Spec = "[-abcd]" x.Spec = "[-a | -b | -c | -d]..."
All of the options can be specified using a special syntax: [OPTIONS]. This is a special token in the spec string (not optionality and not an argument called OPTIONS). It is equivalent to an optional repeatable choice between all the available options. For example, if an app or a command declares 4 options a, b, c and d, then the following two statements are equivalent:
x.Spec = "[OPTIONS]" x.Spec = "[-a | -b | -c | -d]..."
Inline option values are specified in the spec string with the = notation immediately following an option (long or short form) to provide users with an inline description or value. The actual inline values are ignored by the spec parser as they exist only to provide a contextual hint to the user. In the example below, "absolute-path" and "in seconds" are ignored by the parser:
x.Spec = "[ -a=<absolute-path> | --timeout=<in seconds> ] ARG"
The -- operator can be used to automatically treat everything following it as arguments. In other words, placing a -- in the spec string automatically inserts a -- in the same position in the program call arguments. This lets you write programs such as the POSIX time utility for example:
x.Spec = "-lp [-- CMD [ARG...]]" // Allows parsing of the following shell command: // $ app -p ps -aux
Spec Grammar
Below is the full EBNF grammar for the Specs language:
spec -> sequence sequence -> choice* req_sequence -> choice+ choice -> atom ('|' atom)* atom -> (shortOpt | longOpt | optSeq | allOpts | group | optional) rep? shortOp -> '-' [A-Za-z] longOpt -> '--' [A-Za-z][A-Za-z0-9]* optSeq -> '-' [A-Za-z]+ allOpts -> '[OPTIONS]' group -> '(' req_sequence ')' optional -> '[' req_sequence ']' rep -> '...'
By combining a few of these building blocks together (while respecting the grammar above), powerful and sophisticated validation constraints can be created in a simple and concise manner without having to define in code. This is one of the key differentiators between this package and other CLI packages. Validation of usage is handled entirely by the package through the spec string.
Behind the scenes, this package parses the spec string and constructs a finite state machine used to parse the command line arguments. It also handles backtracking, which allows it to handle tricky cases, or what I like to call "the cp test":
cp SRC... DST
Without backtracking, this deceptively simple spec string cannot be parsed correctly. For instance, docopt can't handle this case, whereas this package does.
Default Spec
By default an auto-generated spec string is created for the app and every command unless a spec string has been set by the user. This can simplify use of the package even further for simple syntaxes.
The following logic is used to create an auto-generated spec string: 1) start with an empty spec string, 2) if at least one option was declared, append "[OPTIONS]" to the spec string, and 3) for each declared argument, append it, in the order of declaration, to the spec string. For example, given this command declaration:
docker.Command("run", "Run a command in a new container", func(cmd *cli.Cmd) { var ( detached = cmd.BoolOpt("d detach", false, "Run container in background") memory = cmd.StringOpt("m memory", "", "Set memory limit") image = cmd.StringArg("IMAGE", "", "The image to run") args = cmd.StringsArg("ARG", nil, "Arguments") ) })
The auto-generated spec string, which should suffice for simple cases, would be:
[OPTIONS] IMAGE ARG
If additional constraints are required, the spec string must be set explicitly using the grammar documented above.
Custom Types
By default, the following types are supported for options and arguments: bool, string, int, float64, strings (slice of strings), ints (slice of ints) and floats64 (slice of float64). You can, however, extend this package to handle other types, e.g. time.Duration, float64, or even your own struct types.
To define your own custom type, you must implement the flag.Value interface for your custom type, and then declare the option or argument using VarOpt or VarArg respectively if using the short-form methods. If using the long-form struct, then use Var instead.
The following example defines a custom type for a duration. It defines a duration argument that users will be able to invoke with strings in the form of "1h31m42s":
// Declare your type type Duration time.Duration // Make it implement flag.Value func (d *Duration) Set(v string) error { parsed, err := time.ParseDuration(v) if err != nil { return err } *d = Duration(parsed) return nil } func (d *Duration) String() string { duration := time.Duration(*d) return duration.String() } func main() { duration := Duration(0) app := App("var", "") app.VarArg("DURATION", &duration, "") app.Run([]string{"cp", "1h31m42s"}) }
To make a custom type to behave as a boolean option, i.e. doesn't take a value, it must implement the IsBoolFlag method that returns true:
type BoolLike int func (d *BoolLike) IsBoolFlag() bool { return true }
To make a custom type behave as a multi-valued option or argument, i.e. takes multiple values, it must implement the Clear method, which is called whenever the values list needs to be cleared, e.g. when the value was initially populated from an environment variable, and then explicitly set from the CLI:
type Durations []time.Duration // Make it implement flag.Value func (d *Durations) Set(v string) error { parsed, err := time.ParseDuration(v) if err != nil { return err } *d = append(*d, Duration(parsed)) return nil } func (d *Durations) String() string { return fmt.Sprintf("%v", *d) } // Make it multi-valued func (d *Durations) Clear() { *d = []Duration{} }
To hide the default value of a custom type, it must implement the IsDefault method that returns a boolean. The help message generator will use the return value to decide whether or not to display the default value to users:
type Action string func (a *Action) IsDefault() bool { return (*a) == "nop" }
License
This work is published under the MIT license.
Please see the
LICENSE file for details.
Automatically generated by autoreadme on 2019.02.24
*Note that all licence references and agreements mentioned in the mow.cli README section above are relevant to that project's source code only. | https://go.libhunt.com/mow-cli-alternatives | CC-MAIN-2020-24 | refinedweb | 5,724 | 56.96 |
Thread
Pool
Thread Pool
Thread Pool
Thread Pool
Class
Definition
Provides a pool of threads that can be used to execute tasks, post work items, process asynchronous I/O, wait on behalf of other threads, and process timers.
public ref class ThreadPool abstract sealed
public static class ThreadPool
type ThreadPool = class
Public Class ThreadPool
- Inheritance
-
Examples
In the following example, the main application thread queues a method named
ThreadProc to execute on a thread pool thread, sleeps for one second, and then exits. The
ThreadProc method simply displays a message.."); Thread::Sleep(1000); Console::WriteLine("Main thread exits."); return 0; } // The example displays output like the following: // Main thread does some work, then sleeps. // Hello from the thread pool. // Main thread exits.
using System; using System.Threading; public class Example { public static void Main() { // Queue the task. ThreadPool.QueueUserWorkItem(ThreadProc); Console.WriteLine("Main thread does some work, then sleeps."); Thread.Sleep(1000); Console.WriteLine("Main thread exits."); } // This thread procedure performs the task. static void ThreadProc(Object stateInfo) { // No state object was passed to QueueUserWorkItem, so stateInfo is null. Console.WriteLine("Hello from the thread pool."); } } // The example displays output like the following: // Main thread does some work, then sleeps. // Hello from the thread pool. // Main thread exits.
Imports System.Threading Public Module Example Public Sub Main() ' Queue the work for execution. ThreadPool.QueueUserWorkItem(AddressOf ThreadProc) Console.WriteLine("Main thread does some work, then sleeps.") Thread.Sleep(1000) Console.WriteLine("Main thread exits.") End Sub ' This thread procedure performs the task. Sub ThreadProc(stateInfo As Object) ' No state object was passed to QueueUserWorkItem, so stateInfo is null. Console.WriteLine("Hello from the thread pool.") End Sub End Module ' The example displays output like the following: ' Main thread does some work, then sleeps. ' Hello from the thread pool. ' Main thread exits..)
Remarks.
When you call the QueueUserWorkItem method to queue a method for execution on a thread pool thread. You do this by passing the method a WaitCallback delegate. The delegate has the signature
void WaitCallback(Object state)
Sub WaitCallback(state As Object)
where
stateis an object that contains data to be used by the delegate. The actual data can be passed to the delegate by calling the QueueUserWorkItem(WaitCallback, Object) method.
Note
The threads in the managed thread pool are background threads. That is, their IsBackground properties are
true. This means that a ThreadPool thread will not keep an application running after all foreground threads have exited.
Important
When the thread pool reuses a thread, it does not clear the data in thread local storage or in fields that are marked with the ThreadStaticAttribute attribute. Therefore, when a method examines thread local storage or fields that are marked with the ThreadStaticAttribute attribute, the values it finds might be left over from an earlier use of the thread pool thread..
Note
Unmanaged code that hosts the .NET Framework can change the size of the thread pool by using the
CorSetMaxThreads function, defined in the mscoree.h file..
Note
When demand is low, the actual number of thread pool threads can fall below the minimum values.
You can use the GetMinThreads method to obtain these minimum values.
Caution.
Methods
Applies to
Thread Safety
This type is thread safe. | https://docs.microsoft.com/en-us/dotnet/api/system.threading.threadpool?view=netframework-4.7.2 | CC-MAIN-2019-18 | refinedweb | 536 | 67.45 |
On Thu, Oct 29, 2015 at 4:53 PM, Bert Huijben <bert@qqmail.nl> wrote:
>> 1. In response_buckets.c, when Content-Length and Transfer-Encoding
>> are both present serf goes with Content-Length. The HTTP spec says
>> Transfer-Encoding takes precedence here, and our experience with
>> servers has been that if both are present then Transfer-Encoding is
>> what we should actually pay attention to. We patched this to change:
>>
>> ...
>
> I think we should apply this change. I recently noticed this in the updated HTTP/1.1
specs too.
>
Great!
>> 2. In response_buckets.c serf automatically uncompresses responses,
>> but PageSpeed would rather receive them compressed if they're served
>> that way. Currently we just remove the block:
>>
>> v = serf_bucket_headers_get(ctx->headers, "Content-Encoding");
>> if (v) {
>> /* Need to handle multiple content-encoding. */
>> if (v && strcasecmp("gzip", v) == 0) {
>> ctx->body =
>> serf_bucket_deflate_create(ctx->body, bkt->allocator,
>> SERF_DEFLATE_GZIP);
>> }
>> else if (v && strcasecmp("deflate", v) == 0) {
>> ctx->body =
>> serf_bucket_deflate_create(ctx->body, bkt->allocator,
>> SERF_DEFLATE_DEFLATE);
>> }
>> }
>>
>> Ideally, though, whether to uncompress would be a serf setting.
>
> A new setting can't be backported to 1.3.x, but I don't see why this can't be configurable
in 1.4+
That would be great!
>> 3. We want to be able to check if a connection had error events
>> reported to it during the last call to serf_context_run so that we can
>> manually close it and open a new connection. We added a new API call
>> to outgoing.c to give this information:
>>
>> int serf_connection_is_in_error_state(serf_connection_t* conn)
>> {
>> return ((conn->seen_in_pollset & (APR_POLLERR | APR_POLLHUP)) !=
>> 0);
>> }
>
> I don't think this is really going to work. There are more cases where a connection is
in an error state than just these events. Some platforms report connection errors in a different
way...
>
> Why can't you use serf's own connection resetting? In Subversion we just rely on Serf
resetting connections as needed.
We added this back in May 2011 to fix a problem where serf would spew
dozens of errors each time it got a connection refused. We may not
need it anymore. I'll check.
>
>
>> 4. If you're a CDN, one setup is for someone to CNAME
>> to you and point ref.example.com at their origin. Then you want to
>> fetch from ref.example.com but you need to send "" as
>> the HOST header. So we'd like to set the HOST header separately on
>> requests. We added serf_request_bucket_request_create_for_host for
>> this:
>
> I'm not entirely sure what you try to accomplish here.
Let's say you run something CDN like. People CNAME their pages to
you, and tell you where you can find their origin. In this case
there's (cnamed to you) and ref.example.com (the
origin). A request for comes in, you don't have it in
cache, so you need to fetch it from origin. You need to send a
request to the server at ref.example.com but that server believes it's
name is and might not serve from the right vhost if it
gets a request for ref.example.com. So you want to connect to:
IP: look up "ref.example.com" in DNS
Host: ""
>
> Do you want to send requests to a different host than that you connected to... or explicitly
send a 'wrong' host?
>
Explicitly send the wrong host. That is, use one host string to look
up the IP and another host strong to send in the Host header.
> I would guess that you can just change 'Host' in the setup or request handler of the
request?
> Have you tried that approach?
I don't think so? I'll need to check.
>
>>
>> 5. We want to be able to set a custom certificates directory or file,
>> so we added an API to ssl_buckets.c for that:
>>
>> +apr_status_t serf_ssl_set_certificates_directory(serf_ssl_context_t
>> *ssl_ctx,
>> + const char* path)
>> +{
>> + X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx->ctx);
>> + int result = X509_STORE_load_locations(store, NULL, path);
>> + return result ? APR_SUCCESS : APR_EGENERAL;
>> +}
>> +
>> +apr_status_t serf_ssl_set_certificates_file(serf_ssl_context_t
>> *ssl_ctx,
>> + const char* file)
>> +{
>> + X509_STORE *store = SSL_CTX_get_cert_store(ssl_ctx->ctx);
>> + int result = X509_STORE_load_locations(store, file, NULL);
>> + return result ? APR_SUCCESS : APR_EGENERAL;
>> +}
>
> I'm not sure if this passes the file and path in the right encoding. In general serf
follows apr, which on Windows has a UTF-8 pathstyle, while openssl probably just passes the
path to the ANSI apis on Windows.
>
> We have a serf_ssl_load_cert_file() on trunk that works around these limitations (and
certain openssl linkage problems). We should probably use similar code for these functions.
It sounds like on trunk we would have serf_ssl_load_cert_file() which
we could use here, and then we could manually call it on all the files
in the specified directory.
>
>> 6. We null out ctx->ssl_ctx after it's free'd to help make sure it
>> doesn't get reused:
>>
>> if (!--ctx->ssl_ctx->refcount) {
>> ssl_free_context(ctx->ssl_ctx);
>> + ctx->ssl_ctx = NULL;
>> }
> | http://mail-archives.eu.apache.org/mod_mbox/serf-dev/201510.mbox/%3CCAMJ6YUsggiGZAN--ks=WoBmc0DdEnWFwce92e17Tm8W+qt3U-g@mail.gmail.com%3E | CC-MAIN-2019-47 | refinedweb | 799 | 58.48 |
Recently.
The needs for debouncing a button is a well-understood problem in the embedded development world. Buttons (A.K.A. Pushbuttons, or switches) often generate spurious open/close transitions when pressed, causing by its mechanical design and material it used. These transitions may be read by an MCU as multiple presses and therefore need to be “debounced” either with some extra hardware or some software solution.
The idea of button debouncing is simple, when a button is pressed, you will wait for it to reach a stable state and only then take the button input as the ultimate state, whether it is an ON or an OFF.
Debounce shouldn’t be this complicate
Recently I saw this piece of code when I working on a project which requires me to port some code from one MCU platform to another platform._INTERVAL) { //; }
This nearly 50 lines of code uses a state machine to determine the state of two buttons, it is heavily commented because without those comments, it getting difficult to know what exactly is going on with the logic. It requires a few global variables and some set up to make it work.
typedef enum SWITCH { SWITCH_NONE, SWITCH_START_STOP, SWITCH_LF_RF } switch_t; switch_t switchStatus; switch_t switchValue; switch_t switchMask; typedef enum DEBOUNCE_STATE { DEBOUNCE_STATE_IDLE, DEBOUNCE_STATE_CHECK, DEBOUNCE_STATE_RELEASE } debounceState_t; debounceState_t debounceState;
I don’t like what I saw, how can someone write such complicate software for a simple task of button debouncing? I decided to replace it with a much much simpler solution. But before doing so, I was also curious of what is the “best practise” type of the code used in the Arduino community for button debouncing? So I found this code from Arduino.cc tutorials website, this code has been around for quite sometime, was written by some David Mellis in 2006, and later been modified/enhanced multiple times, one of the person who modified the code is Lady Ada (Limor Fried – the founder/owner of Adafruit). So this code is consider the best practise of code for debouncing and well circulated and quote in various Arduino tutorials.
/* through 220 ohm resistor - pushbutton attached from pin 2 to +5V - 10 kilohm resistor attached from pin 2 to ground - Note: On most Arduino boards, there is already an LED on the board connected to pin 13, so you don't need any extra components for this example. created 21 Nov 2006 by David A. Mellis modified 30 Aug 2011 by Limor Fried modified 28 Dec 2012 by Mike Walters modified 30 Aug 2016 by Arturo Guadalupi This example code is in the public domain. */ //); // set initial LED state digitalWrite(ledPin, led(ledPin, ledState); // save the reading. Next time through the loop, it'll be the lastButtonState: lastButtonState = reading; }
This code is much simpler, easier to understand compare to the previous one. With some effort, it could be re-factor into a function and change some of the global variables into `static` scope to create a self-contained, re-usable
debounce() function. But it is still not as simple as it should be.
The simplest debounce function
The simplest button debounce function that I came across many years ago (and use it ever since in my projects) is the one written by Jack Ganssle in his part 2 of the “A guide to debouncing” article. My version is slight different from Ganssle’s original code, I made it works for Arduino, further simplify the code a little bit, and uses a different value for determine the debounced state.
bool debounce() { static uint16_t state = 0; state = (state<<1) | digitalRead(btn) | 0xfe00; return (state == 0xff00); }
All you need is a button connect between a GPIO pin and ground. There is no other component required, you will need to setup the GPIO pin with internal resistor to
INPUT_PULLUP so the GPIO pin remain HIGH when the button is not been pressed. We write a simple sketch to test the debounce function by toggling the on-board LED every time the button is pressed:
#define btn 2 //assuming we use D2 on Arduino void setup() { pinMode(btn, INPUT_PULLUP); pinMode(LED_BUILTIN, OUTPUT); } void loop() { if (debounced()) { digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN)); } }
When the button is pressed, the button pull the GPIO pin to ground and produce a 0. The value is added into the
state through OR
| operator, and shift up through shift
<< operator each time the button pin is read, the
0xfe00 is a bit mask that mask-out the higher byte, and sort of means that we only care if the lower byte produce a consecutive stream of 0.
When you think of the bouncing problem, the button is in an unstable mode for the initial a few microseconds when it is pressed, and could produce a stream of either 0 or 1 during that few microseconds. If our little function could detect a pattern consists of a stream of 0 after 8 times of reading the button pin, the
state | 0xff00 would produce a true, in another word, the button has reached to a stable state and no longer bouncing around.
This debounce code is easy to understand if you are coming from hardware background or you had experience of using shift-register before. That is because if you think of each read of GPIO pin as a digital clocking signal, the lower 4-bit of the
state as a 4-bit serial-in, parrallel-out shift-register, the output value of true can be produced with an NAND gate as shown below. Of course no one will use this elaborated hardware for debouncing purpose, but the circuit illustrated the algorithm used in our
debounce() function to achieve button debouncing.
This is a simple and elegant debounce function. Just 5 lines of code, easy to understand and self-contain. But it can only handle one button.
Handling multiple buttons
It is not difficult to convert this function to support multiple buttons. I create a simple Arduino library by wrapping the function, the state variable and button setup in a C++ class.
button.h
#ifndef button_h #define button_h #include "Arduino.h" class Button { private: uint8_t btn; uint16_t state; public: void begin(uint8_t button) { btn = button; state = 0; pinMode(btn, INPUT_PULLUP); } bool debounce() { state = (state<<1) | digitalRead(btn) | 0xfe00; return (state == 0xff00); } }; #endif
The code can be downloaded as an Arduino Library from.
You can test the library by adding one more button to Arduino and connect it to D3, and we will write a sketch to using the switch connected to D2 to turn on the built-in LED, and the switch connected to D3 to turn off the LED.
#include "button.h" Button btn1; Button btn2; void setup() { btn1.begin(2); btn2.begin(3); pinMode(LED_BUILTIN, OUTPUT); } void loop() { if (btn1.debounce()) { digitalWrite(LED_BUILTIN, HIGH); } if (btn2.debounce()) { digitalWrite(LED_BUILTIN, LOW); } }
Summary
Button debounce is a well-understood problem in embedded development, and debouncing function has been around since the early day of MCU. Some of the debouncing techniques that widely circulated around the Internet as “best practise” are not necessary the best or simplest button debounce solution. I hope this article will show you the simplest button debounce function that you could use in your Arduino program. For those who are new to Arduino or embedded programming, I would highly recommend to read “A guide to debouncing”.
4 comments by readers
For switch debouncing, sampling at about 10 to 20 times per second is enough.
You need to look for edges so you need to take the differential. dButton/dt !
I read the uP port and xor it with the last read. This can read multiple buttons.
For touch sensors that read analogue levels, I found fricton works.
Instead of the differential, only update the last read if it is significantly different to the last read! has some notes
I had a project using 3 pushbuttons.
Using your library I was able to successfully get it to work, and it was so much better than any of the other debounce programs I spent hours trying to get to work.
#include “button.h”
Button onPin; // the name of the On pushbutton pin
Button resetPin; // the name of the Reset pushbutton pin
Button disconPin; // the name of the Disconnect pushbutton pin
Much thanks.
Hi,
I was wondering if u wrore this incorrectly, or my undertanding is bad.
(Also ur source of this code wrote it swapped, as it doesnt make sense the way u wrote it, imo.)
Good catch. The button.h in the later part of the article and the version on github are using the correct mask of
0xfe00. I had made the correction. | https://www.e-tinkers.com/2021/05/the-simplest-button-debounce-solution/ | CC-MAIN-2021-49 | refinedweb | 1,438 | 56.49 |
A paint device for rendering to a PDF. More...
#include <Wt/WPdfImage>
A paint device for rendering to a PDF.
A WPdfImage paint device should be used in conjunction with a WPainter, and can be used to make a PDF version of a WPaintedWidget's contents.
The PDF is generated using The Haru Free PDF Library, and this class is included in the library only if
libharu was found during the build of the library.
You can use the image as a resource and specialize handleRequest() to paint the contents on the fly. Alternatively can also use write() to serialize to a PDF file (std::ostream). The latter usage is illustrated by the code below:
Wt::Chart::WCartesianChart *chart = ... Wt::WPdfImage pdfImage("4cm", "3cm"); { Wt::WPainter p(&pdfImage); chart->paint(p); } std::ofstream f("chart.pdf", std::ios::out | std::ios::binary); pdfImage.write(f);
A constructor is provided which allows the generated PDF image to be embedded directly into a page of a larger
libharu document, and this approach is used for example by the WPdfRenderer to render XHTML to multi-page PDF files.
Font information is embedded in the PDF. Fonts supported are native PostScript fonts (Base-14) (only ASCII-7), or true type fonts (Unicode). See addFontCollection() for more information on how fonts are located and matched to WFont descriptions.
This paint device has the following limitations:
Create a PDF resource that represents a single-page PDF document.
The single page will have a size
width x
height. The PDF will be using the same DPI (72dpi) as is conventionally used for the desktop.
The passed width and height (such as 4 cm by 3 cm) can be specified in physical units (e.g. 4cm x 3cm), but this will be converted to pixels using the default DPI used in CSS (96dpi) !
Create a PDF paint device to paint inside an existing page.
The image will be drawn in the existing page, as an image with lower-left point (
x,
y) and size (
width x
height).
Adds a font collection.
If Wt has been configured to use
libpango, then font matching and character selection is done by libpango, which is seeded with information on installed fonts by fontconfig. In that case, invocations for this method is ignored. Only TrueType fonts are supported, and thus you need to configure fontconfig (which is used by pango) to only return TrueType fonts. This can be done using a fonts.conf configuration file:
<?xml version='1.0'?> <!DOCTYPE fontconfig SYSTEM 'fonts.dtd'> <fontconfig> <selectfont> <rejectfont> <glob>*.pfb</glob> </rejectfont> </selectfont> </fontconfig>You may need to add more glob patterns to exclude other fonts than TrueType, and also to exclude TrueType fonts which do not work properly with libharu.
If Wt has not been configured to use
libpango, then this method may be used to indicate the location of TrueType). TrueType fonts are preferable over Base-14 fonts (which are PDF's default fonts) since they provide partial (or complete) unicode support.
When using Base-14 fonts, WString::narrow() will be called on text which may result in loss of information.
Finishes painting on the device.
This method is called when a WPainter stopped painting.
Implements Wt::WPaintDevice.
Draws an arc.
The arc is defined as in WPainter::drawArc(const WRectF& rectangle, int startAngle, int spanAngle).
Implements Wt::WPaintDevice.
Returns font metrics.
This returns font metrics for the current font.
Throws a std::logic_error if the underlying device does not provide font metrics.
Implements Wt::WPaintDevice..
Implements Wt::WResource..
Returns the device width.
The device width, in pixels, establishes the width of the device coordinate system.
Implements Wt::WPaintDevice. | http://www.webtoolkit.eu/wt/doc/reference/html/classWt_1_1WPdfImage.html | CC-MAIN-2013-20 | refinedweb | 607 | 57.57 |
How to add other Qml modules?
Hi there,
I am still a newbie in Qml and Ubuntu Touch app development. Now I want to use the QtWebsockets with:
import QtWebSockets 1.0
But when I build the app with clickable, I get the error: module 'QtWebsockets' is not installed
How can I install them? Unfortunately I have no idea how Cmakes or click package format works. I have just used the template from clickable to build plain Qml apps.
@Krille (edit) I've linked your question in the developers groups that I told you, let's wait for an informed answer here.
@krille Brian told me that probably you need to use the old style import for the websockets because of the qt version that is in Ubuntu Touch: | https://forums.ubports.com/topic/1227/how-to-add-other-qml-modules/3 | CC-MAIN-2018-22 | refinedweb | 129 | 80.82 |
27 June 2012 11:34 [Source: ICIS news]
LONDON (ICIS)--The front-month August Brent contract weakened by more than $1.00/bbl on Wednesday, pressured by widening divisions across the eurozone.
By 09:30 GMT, the August ICE Brent contract fell to an intra-day low of $91.70/bbl, a loss of $1.32/bbl compared with Tuesday's settlement. The contract then edged a little higher to trade around $92.20/bbl.
At the same time, the front-month August NYMEX WTI contract was trading around $78.95/bbl, having touched an intra-day low of $78.68/bbl, representing a loss of 68 cents/bbl against Tuesday's close.
?xml:namespace>
Divisions between eurozone countries are being highlighted as
Prices are also being pressured | http://www.icis.com/Articles/2012/06/27/9572907/brent-falls-by-more-than-1bbl-as-eurozone-divisions-widen.html | CC-MAIN-2014-49 | refinedweb | 128 | 69.28 |
i hate pirate of the caraiban but
lol! futuristic jack sparrow!
i hate pirate of the caraiban but
lol! futuristic jack sparrow!
Accepted!
This song just touched my heart and made me dance to it. You worked hard for this song and you should be proud of it. That's all I have to say.
oooh damn!!
This is one mighty fine song :D
at first I thought it was going to be one of those mediocre remixes, but hell was I wrong :D You never dissapoints your fans SkyMarshall and you never cease to amaze me :D
Pretty cool lyrics but I'm not that much of a fan of autotune/vocoder voices :P
The mastering and EQing is superb as always, the beat, the bass, the choice of sounds and synths are perfect.
I loved the part at 1:10, gives the song good variation.
Anyhow, keep up the awesome work 'cause your songs are really amazing :D
5/5
10/10
+fav
Cheers
wow
this is one of the best Pirates remixes that I have heard in a LONG time. Great job. except the 2nd line sounds more like "take your pants off" than "which were fans of". Made it even better when you added the davy jones part in. Great work. Keep it up. Let me know when you put up more music!
10
5
fav'd
def dl'd
FRS
great
dude its refreshing to have some people with some talent and good taste keep it up | https://www.newgrounds.com/reviews/portal/276478/3/date/4 | CC-MAIN-2019-26 | refinedweb | 252 | 88.77 |
This article is translated with (free version) and reviewed by Mincong.
Introduction
During my visit to my family back home in April this year, I came across a lot of technical content in Chinese when I was looking for information, but I also found that not many of them have good quality. So I started to write Chinese articles in my blog, hoping to contribute to the Chinese developer community. More concretely, I wrote in two languages: Chinese and English. But in practice, I found that it is not a good experience for reader to see two languages in one blog.
After I started writing in Chinese, several times my colleagues found my popular English articles in Google Search and started reading them. This thing made me embarrassed, because since April, my articles are all in Chinese. Let me think about it from their point of view: what happens if after reading, they are curious to read more articles? They may click on the home page and then surprised to see a bunch of Chinese blogs: they may feel confused and feel like they are in the wrong place. For someone who doesn’t know another language, the experience can be very bad. The opposite also holds true: when a Chinese friend sees my blog and sees a bunch of English articles, it feels hard to get interested in reading them. If the articles are written in their native language, it will be much more user-friendly.
That’s why I want to do internationalization: I want to provide a comfortable reading experience for every reader. I want to have a clear distinction between the different languages in the blog, so that when people visit, they can read the content in the language they are familiar with, no matter which page they click on. Then the blog itself can also provide options for people to switch to another language.
This post will share with you the internationalization of my blog.
Proposals
There are serveral proposals for internationalization, and I’ll discuss their feasibility below.
- Provide translation feature. Embed translation button in the article and use third-party translators (Bing, Google, DeepL, etc.) to translate when user clicks the translation button.
- Interlink English and Chinese articles. Embed a link to English article in Chinese article and another link to Chinese article in English article.
- Introduce the concept of page key. Chinese and English articles share the same page key.
- Use two collections:
postsand
cn.
Final plan: Use two collections.
Proposal 1: Provide Translation Feature
Embed a translation button inside the article and use a third-party translator (Bing, Google, DeepL, etc.) to translate when the translation button is clicked. The rationale is that my blog is not very visited, with about 18,000 visitors per month. And I am not a professional writer, purely writing for fun and not making money. There is no need to be so serious. This feature is inspired by Chrome’s Translate button, which allows you to translate a page in a non-frequently used language by clicking the Translate button in the URL input field, or by right-clicking on the page content.
The advantages of this proposal are:
- It’s easy to implement
The disadvantages of this proposal are:
- There are no two articles, there is only one.
- No correction for translation results
- Without articles, we can’t attract readers through articles
Proposal 2: Interlinking English and Chinese Posts
Add a link to the corresponding article at the beginning of each article in order to switch languages. That is, embed a link to an English article in a Chinese article and a link to a Chinese article in an English article. On the web page, add a button or an icon to achieve language switching. This way, readers can access another language version of the article by clicking this button or this icon while reading.
For example, for the article “Implementing backward-compatible schema changes in MongoDB”, the switch between the English and Chinese versions of the article can be implemented in the following form.
English version.
--- layout: post title: Making Backward-Compatible Schema Changes in MongoDB date: 2021-02-27 17:07:27 +0100 categories: [java-serialization, reliability] tags: [java, mongodb, serialization, jackson, reliability] comments: true + lang: en + version: + en-CN: 2021-04-30-mongodb-schema-compatibility.md ... ---
Chinese version.
--- layout: post title: Is it really that easy to add and delete fields in MongoDB? date: 2021-04-30 23:09:38 +0800 categories: [java-serialization, reliability] tags: [java, mongodb, serialization, jackson, reliability] comments: true + lang: zh + version: + en-US: 2021-02-27-mongodb-schema-compatibility.md ... ---
The advantages of this proposal are:
- The links to existing articles remain unchanged and do not affect SEO
The disadvantages of this proposal are:
- It is not possible to know the link of another version of the other article through the article link.
- If you change the link to the article, you should remember to change the referer, i.e. in the other language page.
Proposal 3: Shared Page Key between Chinese and English
Introduce the concept of page key in each article. When a user accesses the article, the page URL contains both the language and the page key. More precisely, it follows the following expression.{lang}/{page-key}
English version (ideal state).
--- layout: post title: Making Backward-Compatible Schema Changes in MongoDB date: 2021-02-27 17:07:27 +0100 categories: [java-serialization, reliability] tags: [java, mongodb, serialization, jackson, reliability] comments: true + key: mongodb-schema-compatibility + lang: en ... ---
Chinese version (ideal state).
--- layout: post title: Is it really that easy to add and delete fields in MongoDB? date: 2021-04-30 23:09:38 +0800 categories: [java-serialization, reliability] tags: [java, mongodb, serialization, jackson, reliability] comments: true + key: mongodb-schema-compatibility + lang: zh ... ---
The advantage of this proposal are:
- disadvantages of this proposal are:
- May affect SEO
Originally this was my perferred solution. Unfortunately it is not possible to implement. Because not all variables are available as part of Jekyll’s permalink. For example, Jekyll does not support custom variable
lang as part of a link. See the official documentation Permalinks for variables supported by Permalinks.
Proposal 4: Use Two Collections
The first collection is the default
posts and the second collection is
cn.
The advantage of this is the same as proposal 3:
- downside of this are:
- The default plugin
jekyll-paginateonly supports pagination for the default collection posts. If you need to paginate another collection, you need to use the
jekyll-paginate-v2plugin. However, GitHub Pages does not officially support the
jekyll-paginate-v2plugin.
Other Considerations
- Whether the theme you are currently using has support for internationalization? For example, I use Jekyll TeXt Theme, which has some support for internationalization itself. The information in the header and footer of the browsing page can be automatically adjusted according to the language of the page. However, it does not translation for the page content directly.
- If you’re using GitHub Pages, consider whether GitHub Pages has support for the plugins that you use. Only some of the Jekyll plugins are officially supported by GitHub, and others won’t work even if you install them. This will affect you unless you don’t use the official site generation, you can generate pages locally yourself or generate them from your custom CI pipeline.
- Consider using another Jekyll internationalization plugin, such as jekyll-multiple-languages-plugin. I didn’t look into it at the time I wrote the proposals, and only found out about this plugin after the project was done… But this plugin is not supported by GitHub Pages neither.
Other Websites
How do other blogs work? Is there anything we can learn from them?
Elasticsearch Blog
Elastic’s blog is internationalized, and each article is available in multiple languages, such as the following article: How to design a scalable Elasticsearch data storage architecture.
It is listed below in three languages.
It is named in the following way.{post}{country}/blog/{post}
English blogs do not have EN prefix, other languages use country abbreviation as prefix, for example, CN for China, JP for Japan.
TeXt Theme
Jekyll TeXt Theme is a highly customizable Jekyll theme for personal or team websites, blogs, projects, documents and more. It references the iOS 11 style with big and prominent headers and rounded buttons and cards. It was written by Alibaba’s engineer Tian Qi (kitian616). This theme supports internationalization. In fact, the documentation of this theme itself is internationalized. If you don’t believe me, see this table:
It is named in the following way.{lang}/{post}
Whatever the language, the language abbreviation is used as the prefix, for example, zh for Chinese, en for English.
Final solution
The final solution is proposal 4: use two collections. The first collection is the default
posts and the second collection is
cn. The main goal is to modify the article links to the following format.{country}/{post}{country}/{page}
The two parts of the link here.
countryis the country, EN for English-speaking countries and CN for China. This expression was better than using locale en/zh because it’s not only a matter of language, but also the components loaded by the page: for example, the Chinese page will suggest WeChat but not the English version. In the future, I’ll also consider splitting the other components into two different versions: Chinese and English pages load different comment systems, different SEO scripts, etc.
- The
postor
pageis the ID of the blog post or the ID of another page.
Next, I want to share with you the specific tasks that need to be done when implementing internationalization.
Tasks
This section is a detailed explanation of the main tasks that need to be done. This section may be a bit long, it’s mainly for those who are interested in changing their blogs for real. If you don’t want to internationalize your site, I suggest avoid reading it into details.
Task 1: Modify Chinese Articles
Modify the article link to the following format.{post}
Since most of the Chinese articles were written after April this year, there is no need to keep the original links. At the beginning of each article, add two pieces of information: language and link redirection.
+ lang: zh date: 2021-04-20 11:21:16 +0800 categories: [java-core] tags: [java, akka] @@ -13,6 +14,8 @@ excerpt: > image: /assets/bg-ocean-ng-L0xOtAnv94Y-unsplash.jpg cover: /assets/bg-ocean-ng-L0xOtAnv94Y-unsplash.jpg + redirect_from: + - /2021/04/20/exponential-backoff-in-akka/ article_header:
Then create a new collection called
cn. Store it in the folder
_cn according to Jekyll naming requirements, then put all Chinese articles in that folder and remove the “year, month and day” part of the file name.
Changes in article links.
- Before:
- After:
In addition, in the global configuration file (
_config.yml), configure the information about the
cn collection, such as the permalink, whether to display the table of contents, etc. For details, see:
Task 2: Modify English Articles
I have 168 English articles on my blog, some of which have important page views. I don’t want them to lose any information because of the internationalization, such as comments and likes on Disqus. So my strategy for English articles is to not make any changes to existing articles and only change the new articles. For new articles, I use the new naming convention{post}. In the following paragraphs, let’s discuss it further.
For all existing articles, explicitly mark the article language as English in the front matter at the article level.
find _posts -type f -exec sed -i '' -E 's/date:/i lang: en' {} +
And after adding
permalink so that they are not interfered with by the global configuration.
#! /bin/bash paths=($(find "${HOME}/github/mincong-h.github.io/_posts" -type f -name "*.md" | tr '\n' ' ')) i=0 for path in "${paths[@]}" do filename="${path##*/}" year=$(echo $filename | sed -E 's/^([[:digit:]]+)-([[:digit:]]+)-([[:digit:]]+)-(. *)\.md/\1/') month=$(echo $filename | sed -E 's/^([[:digit:]]+)-([[:digit:]]+)-([[:digit:]]+)-(. *)\.md/\2/') day=$(echo $filename | sed -E 's/^([[:digit:]]+)-([[:digit:]]+)-([[:digit:]]+)-(. *)\.md/\3/') name=$(echo $filename | sed -E 's/^([[:digit:]]+)-([[:digit:]]+)-([[:digit:]]+)-(. *)\.md/\4/') permalink="/${year}/${month}/${day}/${name}/" echo "${i}: year=${year}, month=${month}, day=${day}, name=${name}, permalink=${permalink}" sed -i '' -E '/comments:/i\ permalink: PERMALINK ' "$path" sed -i '' "s|PERMALINK|${permalink}|" "$path" i=$((i + 1)) done
For new articles, use the new naming convention (
_config.yml).
- permalink: /:year/:month/:day/:title/ + permalink: /en/:title/
Also you need to modify the post generation script
newpost.sh to make it generate both Chinese and English posts. Here is an excerpt from the script: we generate the paths for both Chinese and English posts, confirm that they do not exist, and then add new content.
title="${*:1}" if [[ -z "$title" ]]; then echo 'usage: newpost.sh My New Blog' exit 1 fi bloghome=$(cd "$(dirname "$0")" || exit; pwd) url=$(echo "$title" | tr '[:upper:]' '[:lower:]' | tr ' ' '-') filename="$(date +"%Y-%m-%d")-$url.md" filepath_en="${bloghome}/_posts/${filename}" filepath_cn="${bloghome}/_cn/${filename}" if [[ -f "$filepath_en" ]]; then echo "${filepath_en} already exists." exit 1 fi if [[ -f "$filepath_cn" ]]; then echo "${filepath_cn} already exists." exit 1 fi append_metadata_en "$filepath_en" "$title" append_metadata_cn "$filepath_cn" "$title" # Not for EN, because EN post is translated. append_content "$filepath_cn" echo "Blog posts created!" echo " EN: ${filepath_en}" echo " CN: ${filepath_cn}"
For more details, see:
Task 3: Adding a Chinese Homepage
Adding a Chinese homepage sounds easy, as if all you need to do is copy
index.html from the blog home page to
cn/index.html and translate a few words. Actually, it is way more complex than that. I use the official Jekyll plugin jekyll-paginate (v1) for my home page. But this plugin only supports pagination for the default set
posts, not for other sets, such as
cn. So the real meaning of adding a Chinese homepage is to upgrade the plugin to jekyll-paginate-v2 to support pagination for the Chinese collection
cn.
Install and use the new plugin in the site configuration (
_config.yml) at
- paginate: 8 - paginate_path: /page:num # don't change this unless for special need + pagination: + enabled: true + per_page: 8 ## => Sources @@ -238,7 +240,7 @@ defaults: ############################## plugins: - jekyll-feed - - jekyll-paginate + - jekyll-paginate-v2
Modified the paginator of the TeXt Theme theme itself to avoid using
site.posts directly as a source for posts. And also add a specific prefix to the homepage, so that English and Chinese have their own homepage, i.e. and.
- {%- assign _post_count = site.posts | size -%} + {%- assign _post_count = paginator.total_posts -%} {%- assign _page_count = paginator.total_pages -%} <p>{{ _locale_statistics | replace: '[POST_COUNT]', _post_count | replace: '[PAGE_COUNT]', _page_count }}</p> <div class="pagination__menu"> @@ -51,7 +51,7 @@ </li> {%- elsif page == 1 -%} - {%- assign _home_path = site.paths.home | default: site.data.variables.default.paths.home -%} + {%- assign _home_path = site.paths.home | default: site.data.variables.default.paths.home | append: include.baseurl -%} {%- include snippets/prepend-baseurl.html path=_home_path -%}
There are actually some other modifications to consider, but I won’t expand on them due to the timing. Here is the final result for the home page, a comparison between English and Chinese:
For more details see:
Task 4: Modifying Build and Deployment
You can no longer use the old automatic deployment method because of jekyll-paginate-v2, a plugin that is not officially supported by GitHub. Now you need to deploy it manually or via the CI. That is, you no longer deploy from the
master branch. After the code is merged into
master, the new pages are generated manually or by CI (core command:
jekyll build). Then, the generated content, which is in the folder
_site, is uploaded to the
gh-pages branch for deployment.
To do it manually, the main steps are as follows: create a new, master-independent branch
gh-pages, add an empty commit as the start of the branch, then empty the local Jekyll generated files folder
_site and connect it to the new branch
gh-pages
git checkout --orphan gh-pages git commit --allow-empty -m "Initialize gh-pages" rm -rf _site git worktree add _site gh-pages # "jekyll build" or equivalent commands
To implement this task, you also need to change the branch to deploy from
master to
ph-pages in the GitHub project settings.
For more information, see: Sangsoo Nam, Using Git Worktree to Deploy GitHub Pages, 2019.
To do it via the CI (GitHub Actions in my case), you can use the following workflow:
name: Deploy to GitHub Pages on: push: branches: - master - docker # testing jobs: build-and-deploy: runs-on: ubuntu-latest env: JEKYLL_ENV: production steps: - name: Checkout source code uses: actions/checkout@v2 with: persist-credentials: false - name: Set up Ruby uses: ruby/setup-ruby@v1 with: ruby-version: 2.6 # Not needed with a .ruby-version file bundler-cache: true # runs 'bundle install' and caches installed gems automatically - name: Install dependencies in the Gemfile run: | bundler install --path vendor/bundle - name: Build Jekyll website run: | bundle exec jekyll build - name: Deploy GitHub Pages uses: JamesIves/github-pages-deploy-action@4.1.4 with: branch: gh-pages folder: _site
Task 5: Modifying More Pages
In the task above, we mainly mentioned modifications for Chinese articles and English articles. But a website has many other pages besides articles, such as categories, series, archives, about, etc. These pages also need to be modified before they can be used properly.
The main objective is to ensure a consistent user-experience for browsing. When navigating between pages, all links in English pages will lead to English pages, and all links in Chinese pages will lead to Chinese pages. This creates a comfortable reading experience for the user: because all pages are in a language they are familiar with. As for the pages that already exist, we need to redirect them to the new links. The following is a list of new pages and the redirection of existing pages.
Category pages:{category}/{category}/ ->{category} ->{category}/
Series pages:{serie}/ ->{serie} ->{serie}/
About page: ->
Archived pages: ->
For more information, see:
Task 6: Language Switching Button
Provide a language switch button in the website to enable languange switching. There are two main buttons here: one in the top right corner of the page, displayed as a flag, and another button in the title section of the article, highlighted in red for the current language and white for the optional other languages. The difference between these two buttons is that the top-right button will switch to the home page in another language when clicked, while the language button on the page will make the page jump directly to another version of the same article. I call them “global switching” and “article switching” feature.
For the global switching feature, the main tasks are to write the flag, link, and other information of another language in the configuration file of the page navigation, and then use these information when the page is generated.
Register information to the data file of the page navigation (
_data/navigation.yml).
site: ... # switch to the other langage urls2: en : /cn/ zh : / urls2_src: en : /assets/flag-CN.png zh : /assets/flag-US.png urls2_alt: en : "Switch to Chinese" zh : "Switch to English"
The header (
_includes/header.html) should include this element as well.
<li> <a href="{{ _site_root2 }}"> <img src="{{ _site_root2_src }}" alt="{{ _site_roo2_alt }}" class="navigation__lang_img"> </a> </li>
For the local toggle feature, the implementation is quite different. This is achieved by looking for articles with the same name in a collection of other languages. Here, articles in different languages must use the same filename, otherwise they cannot be found. Specifically, we first get the article ID, then extract the characters after the last slash
/ (with the slash
/), then take this information to traverse other collections and return the corresponding link:
{% assign _id = include.article.id %} {% assign _filename = _id | split:"/" | last %} {% assign _suffix = _filename | prepend: "/" %} {% assign _matched = include.collection | where_exp: "item", "item.id contains _suffix" | first %} {% if _matched %} {% assign __return = _matched.url %} {% else %} {% assign __return = nil %} {% endif %}
For more information, see.
-
-
Remaining Tasks
Having done this, the entire internationalization task is basically done. The following tasks can be addressed in the future to improve the situation:
- Implement both Chinese and English RSS feeds.
- Load more Chinese components on Chinese pages, such as loading WeChat’s SDK for sharing, loading Baidu’s SDK to improve search presence on Chinese search engine, replacing Disqus with another commenting system that can be loaded in mainland China without VPN, and links to other Chinese developer platforms.
- Automate the Chinese-to-English translation by scripting translation requests directly to third-party translation platforms, such as Google Translate, DeepL, etc.
- Fix the tag-cloud feature in the archive page. The tag-cloud currently uses
site.tagsfor tag-related statistics. However, all the tags of Chinese articles (under the
cncollection) are not taken into account.
- Fix the article category pages. Now the category page can show text in Chinese, but the actual article list is retrieved from English collection
postsrather than Chinese collection
cn.
If you have other suggestions, please feel free to leave a comment!
Going Further
How to go further from this article?
- If you’ve never heard of Jekyll, you can visit official website to learn about this great blogging engine.
- If you’ve never tried the free GitHub Pages, visit the official website and try to build your and host your own personal blog for free!
- If you haven’t tried Jekyll TeXt Theme by Qi Tian, maybe you would like to try it.
- If you want to learn more about jekyll-paginate-v2, you can visit their GitHub project.
Conclusion
In this article, we have seen the process of internationalizing of this site, an internationalization based on Jekyll and TeXt Theme. We compared the pros and the cons of the four proposals; we looked at other blogs’ implementations of internationalization; we listed the six of the more important tasks; and we looked further into the next steps for internationalization. Finally, I also share some resources for you to going further from this article. I hope this article has given you some insights. If you’re interested in more information and advice, please follow me on GitHub mincong-h. Thank you all!
References
- Elastic, “Elastic Blog”, Elastic, 2021.
- MrPowerScripts, “How to get around the jekyll-pagination-v2 limitation of GitHub pages with CircleCI”, MrPowerScripts, 2019.
- Sangsoo Nam, “Using Git Worktree to Deploy GitHub Pages”, Sangsoo Nam, 2019.- worktree-to-deploy-github-pages.html
- Jekyll, “Jekyll Documentation”, Jekyll, 2021.
- Sverrir Sigmundarson, “jekyll-paginate-v2”, GitHub, 2021.
- Tian Qi, “Internationalization”, TeXt Theme, 2021.
- Rahul Patil, “How to insert text after a certain string in a file?”, Unix & Linux - Stack Exchange, 2014.. stackexchange.com/a/121173/220624
- Taewoo Lee, “[Jekyll](EN) Make array and add element in liquid”, TWpower’s Tech Blog, 2020.- make-array-and-add-element-in-jekyll-liquid-en | https://mincong.io/en/jekyll-i18n/ | CC-MAIN-2021-49 | refinedweb | 3,809 | 55.13 |
Greedy, suboptimal solver for the Travelling Salesman Problem
Project description
Suboptimal Travelling Salesman Problem (TSP) solver
In pure Python.
This project provides a pure Python code for searching sub-optimal solutions to the TSP. Additionally, demonstration scripts for visualization of results are provided.
The library does not requires any libraries, but demo scripts require:
- Numpy
- PIL (Python imaging library)
- Matplotlib
The library works under both Python 2 and 3.
Modules provided:
- tsp_solver.greedy : Basic greedy TSP solver in Python
- tsp_solver.greedy_numpy : Version that uses Numpy matrices, which reduces memory use, but performance is several percents lower
- tsp_solver.demo : Code for the demo applicaiton
Scripts provided
- demo_tsp : Generates random TSP, solves it and visualises the result. Optionally, result can be saved to the numpy-format file.
- tsp_numpy2svg : Generates neat SVG image from the numpy file, generated by the demo_tsp.
Both applications support a variety of command-line keys, run them with --help option to see additional info.
Installation
Install from PyPi:
# pip install tsp_solver2
or
$ pip install --user tsp_solver2
(Note taht tsp_solver package contains an older version).
Manual installation:
# python setup.py install
Alternatively, you may simply copy the tsp_solver/greedy.py to your project.
Usage
The library provides a greedy solver for the symmetric TSP. Basic usage is:
from tsp_solver.greedy import solve_tsp #Prepare the square symmetric distance matrix for 3 nodes: # Distance from A to B is 1.0 # B to C is 3.0 # A to C is 2.0 D = [[], [1.0], [2.0, 3.0]] path = solve_tsp( D ) #will print [1,0,2], path with total length of 3.0 units print(path)
The triangular matrix
D in the above example represents the following graph with three nodes A, B, and C:
Square matrix may be provided, but only left triangular part is used from it.
Utility functions
tsp_solver.util.path_cost(distance_matrix, path) Caclulate total length of the given path, using the provided distance matrix.
Using fixed endpoints
It is also possible to manually specify desired start and/or end nodes of the path. Note that this would usually increase total length of the path. Example, using the same distance matrix as above, but now requiring that path starts at A (index 0) and ends at C (index 2):
D = [[], [1.0], [2.0, 3.0]] path = solve_tsp( D, endpoints = (0,2) ) #will print path [0,1,2] print(path)
New in version 0.4: it is not possible to specify only one of two end points:
solve_tsp( D, endpoints = (None,2) ) solve_tsp( D, endpoints = (0,None) )
Round trip paths
To find a round trip path, that returns to the starting node, specify the same value to both endpoints:
path = solve_tsp( D, endpoints = (0,0) ) #will print path [0,1,2,0] print(path)
Note that round trip paths are one step longer.
Neither solution quality nor complexity depends on the endpoints specified, so it is safe to use (0,0) when don't care.
Algorithm
The library implements a simple "greedy" algorithm:
- Initially, each vertex belongs to its own path fragment. Each path fragment has length 1.
- Find 2 nearest disconnected path fragments and connect them.
- Repeat, until there are at least 2 path fragments.
This algorightm has polynomial complexity.
Optimization
Greedy algorithm sometimes produces highly non-optimal solutions. To solve this, optimization is provided. It tries to rearrange points in the paths to improve the solution. One optimization pass has O(n^4) complexity. Note that even unlimited number of optimization paths does not guarantees to find the optimal solution.
Performance
This library neither implements a state-of-the-art algorithm, nor it is tuned for a high performance.
It however can find a decent suboptimal solution for the TSP with 4000 points in several minutes. The biggest practical limitation is memory: O(n^2) memory is used.
Demo
To see a demonstration, run
$ make demo
without installation. The demo requires Numpy and Matplotlib python libraries to be installed.
Testing
To execute unit tests, run
$ make test
Change log
Version 0.4.1
Added possibility to search for round trip paths, when endpoints coincide.
Version 0.4
Added possibility to specify only one of end points.
Project details
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/tsp-solver2/ | CC-MAIN-2021-43 | refinedweb | 715 | 58.28 |
James Estrada17,822 Points
Can somebody explain the special method __repr__?
Kenneth explains that by using:
def __repr__(self): return str(self.value)
we know what values we are getting whenever we call our instance.
I checked on the console and in fact, if I remove the repr I get back a list of objects spitted out whenever I call the instance. But if I use it , I get back a list of ints. Why are we getting back ints if we converted self.value to a string? How does the repr work?
1 Answer
Cooper Runstein11,795 Points
repr and str are very similar in their purpose, however I learned (And this isn't by any means the only way to do it) that repr should be a representation of how the class is made. So for example:
class Value: def __init__(self, value): self.value = value def __str__(self): return str(self.value) def __repr__(self): return 'Value({})'.format(self.value)
The point of repr is to give representation to your object so when you or another developer checks it out in the console you're not just seeing a memory location.
I'd also take a guess that you're seeing a string that just looks like an int in the console when you inspect the object, but if not, something weird is going on.
Lastly, Python has some default behaviors that you should know about, if you create a class and only give it a repr, you can still use the str() method on your class, python looks for the repr if str doesn't exist. That brings me to your question of how repr works, all the dunder methods have "under the hood" behaviors that python uses, and I have no clue exactly how they all work, nor do I need to, and you probably don't either. What you should know is that python uses repr to replace the default memory location representation of your object with a representation of your object you give it.
James Estrada17,822 Points
I played around with the repr to give my objects a different representation just like you advised, and indeed I understood it better. Thank you!
Cooper Runstein11,795 Points
Cooper Runstein11,795 Points
Also I realize Kenneth doesn't follow the same form with repr vs str, but if you change your repr to be something other than just a value you might understand it a bit better. | https://teamtreehouse.com/community/can-somebody-explain-the-special-method-repr | CC-MAIN-2020-10 | refinedweb | 413 | 67.69 |
// This is a work-in-process procedural map generator for an idea of mine.
// For now, I am generating the co-ordinates of the map and then display them.
// With the 'room' structure in place I should be able to create larger and more detailed packages for the rooms which form the 'building blocks' of the map.
#include <iostream>
#include <conio.h>
#include <fstream>
#include <windows.h>
#include <stdlib.h>
#define PAUSE _getch() // This line of code will ask the user for input, and upon getting a character (which is then technically entered into no existing variable) continues running. Useful for debugging.
using namespace std;
struct room
{
double id;
int x;
int y;
char displaysymbol;
};
int mapxsize;
int mapysize;
room * map; // We designate a dynamic array of type 'room'.
room roomgenerator (int roomx, int roomy);
void mapdisplay (room *map);
int randomnumber (int range_min, int range_max);
int main()
{
cout << "NP map generator\n\n";
cout << "Please enter the intended x- and y-sizes for the map.\nThe maximum size is 20x20 tiles.\n\n";
do //The program checks whether the suggested x-size is within the allowed limits.
{
cout << "Size (x): ";
cin >> mapxsize;
if (mapxsize > 20 || mapxsize < 1)
{
cout << "Please type a valid value between 0 and 21!\n";
}
} while (mapxsize > 20 || mapxsize < 1);
do //The program checks whether the suggested y-size is within the allowed limits.
{
cout << "Size (y): ";
cin >> mapysize;
if (mapysize > 20 || mapysize < 1)
{
cout << "Please type a valid value between 0 and 21!\n";
}
} while (mapysize > 20 || mapysize < 1);
map = new (nothrow) room [mapxsize*100+mapysize]; // I create a dynamic memory unit here. Note that it is not completely efficient with space. This is because of the way I allocate the rooms to their own numbers.
if (map == 0)
{
cout << "Errorcode MG01: Failure assigning memory.";
exit (EXIT_FAILURE);
PAUSE;
}
cout << "\n";
int roomx;
int roomy;
for (roomx=1; roomx<=mapxsize; roomx++) // I run the roomgenerator once for every room to be generated.
{ for (roomy=1; roomy<=mapysize; roomy++)
{
roomgenerator (roomx,roomy);
}
}
cout << "\n\nMapdisplay will now run.";
PAUSE;"; // Sloppy code to 'clear' the console. I will later replace it, but for practice and debugging purposes, it is alright.
mapdisplay (map);
PAUSE;
delete map;
return 0;
}
room roomgenerator (int roomx, int roomy)
{
map [(roomx-1)*100+(roomy-1)].id = roomx*100+roomy; // In the 'map' array, we generate a room with a number that is 100*x + Y. For the map with coordinates x = 10 and y = 15, for instance, we would get number '1015'. This is also its slot in the array.
map [(roomx-1)*100+(roomy-1)].x = roomx;
map [(roomx-1)*100+(roomy-1)].y = roomy;
map [(roomx-1)*100+(roomy-1)].displaysymbol = '+';
cout << "Room number " << map [(roomx-1)*100+(roomy-1)].id << "\n";
cout << "x = " << map [(roomx-1)*100+(roomy-1)].x << " y = " << map [(roomx-1)*100+(roomy-1)].y << "\n\n";
return map [(roomx-1)*100+(roomy-1)];
}
void mapdisplay (room *map) // This code will be expanded along with the variables contained in the 'room' structure and then ported into a different part of the final program.
/* The mapdisplay displays the cahracter assigned to every room. For now, that's just plusses. */
{
cout << "This is the grid of coordinates:\n\n\n\n";
for (int roomx = 1; roomx<=mapxsize; roomx++)
{
cout << "\n";
for (int roomy = 1; roomy<=mapysize; roomy++)
{
cout << map [(roomx-1)*100+(roomy-1)].displaysymbol;
}
}
}
int randomnumber (int range_min, int range_max)
{
int result = 0;
cout << "Hello! I am a function that is not called yet because I do absolutely nothing. I serve as a placeholder until my beginning programmer learns how to actually generate a random number! Then I will be used for all sorts of things!";
cout << "\nI am so excited! What if I will be used to generate random types of rooms and contents and all other kinds of information?! And what if the number I return can be modified for all sorts of different functions?! Wow!";
return result;
} | http://www.cplusplus.com/forum/beginner/105759/ | CC-MAIN-2017-04 | refinedweb | 660 | 74.69 |
Hey there, when designing an API, I sometimes get to the point where I want to wrap some method parameters into an object, so I can later add additional parameters without breaking the API or bloating it with method overloads. Also this allows better documentation/handling of default and optional values. If I used a constructor […]
Month: February 2017
Setting Variables In My Powershell Profiles
So based on some recommendations in my thread here, I have started working in VSCODE since it supports to MFA for exchange online/Azure AD Online. One of the limitations i have found is that unlike ISE each new file is isolated inside itself and all modules ( Azure AD, Office 365) need to be […]
Grasshopper is a code-first 3D game engine written entirely in C#
Resources for learning about securing a Linux VM(.Net Core hosting)?
message box
this is my code and it works Public Class frmLoto Inherits System.Windows.Forms.Form Dim random As Random Private Sub frmLoto_Load(sender As Object, e As EventArgs) Handles MyBase.Load End Sub Private Sub picLogo_Click(sender As Object, e As EventArgs) Handles picLogo.Click End Sub Private Sub cmdRoule1_Click(sender As Object, e As EventArgs) Handles cmdRoule1.Click Dim cmdRoule1 As Integer Dim […]
Azure Portal Dashboard showing deleted services
Circular Nested AD Groups
I was given a request to provide a function for our staff to run that can dump group memberships out to a file. Easy enough, except after having done this a while, I started thinking about edge cases, and the one I’m concerned about is circular nested groups. I run this script periodically to confirm […]
This always struck me as something between “I learned coding on older languages and won’t change” and “I’m to lazy to do this a better way”…
Get Full Name of Namespace, Can’t Use nameof
Hi! I’m trying to get help for a problem I’m facing. I am doing reflection on an assembly & am trying to appropriately get the name of a namespace. If I use: string namespace = nameof(somenamespace.anothernamespace); … then the value returned is “anothernamespace”. This causes problems when I try to do the following: if (someType.Namespace […] | http://howtocode.net/2017/02/page/2/ | CC-MAIN-2018-47 | refinedweb | 368 | 50.77 |
- 0shares
- Facebook0
- Twitter0
- Google+0
- Pinterest0
- LinkedIn0
Basic Input/Output:
Standard Output
The information or the processed data given by the computer is known as output. The output that is displayed on the monitor is the hardcopy and the printed form of output is a softcopy. In C++ programming language we use various outputs.
Some important output functions in C++ are as follows:
- cout<<
- puts()
The functions used for input and output are stored in the header file <iostream>. Header file is necessary to include in the program it input/output functions are used.
Cout<< Function:
This function is used to display output on the monitor. It can display text, constants or values of variables.
SYNTAX
The syntax of cout is as follows:
cout<<”Format string”;
cout<<variable_name;
It can also be used as:
Cout<<”Format string”<<variable_name;
Format string is given in double quotes as shown. It is also called control string. Format string may include text that is the message to be printed, escape sequences that are used to specify the format of output e.g. \n, \t, etc.
Variable name is the variable whose value is going to be printed.
EXAMPLE
Following example is a program that displays a message and values of integer and character variables.
#include<iostream>
Using namespace std;
void main()
{
int n=10;
char ch=’*’;
cout<<”testing output”;
cout<<n;
cout<<endl;
cout<<”testing output”<<ch;
}
Working of the above program:
The above program declares and initializes two variables n and ch. It displays message “testing output” on the screen. it then displays the values of n and ch.
Escape sequences
These are the special characters used in format string to modify the format of output. These characters are not displayed in the output. These characters always begin with backslash “\”. The backslash is known as escape character.
Some of the escape sequences are as follows:
The escape sequences are written in double quotes or format string in cout statement.
Standard Input
The process of giving something to the computer is known as input. The input is mostly given by keyboard. The term standard input refers to the input using keyboard. A program may need certain input from the user for working properly. C++ programming language provides many functions to get input from the user.
Some important input functions are as follows:
- cin>>
- gets()
- getch()
- getche()
Cin>> Function
This function is used to get input from the user. The input is stored in a variable in a specified form.
SYNTAX
the syntax of cin is as follows:
cin>>variable_name;
variable name is the name of that variable whose value will be entered by the user.
EXAMPLE
Program to convert distance from kilometers into meters.
# include<iostream>
Using namespace std;
void main()
{
float k;
double m;
cout<<”enter distance in kilometers”;
cin>>k;
m=k*1000;
cout<<k<<“\nkilometers = “<<m;<< “meters = “;
}
getch() function:
The word getch() stands for get character. The function is used to input single character from the user. When this function is executed, it waits for any key to be pressed. The character entered by the user is not displayed on the screen.
The function getch() is defined in the header file conio.h. this header file must be included in the program to use this function.
SYNTAX
The syntax of getch() function is as follows:
getch();
Another way to use this function is as follows:
variable = getch();
variable indicates the variable in which the character is stored. The use of variable is optional.
This function is normally used in the program to stop execution of program temporarily. For example, the user can use it at the end of program so that the control remains on DOS screen until the user presses any key.
EXAMPLE
# include<iostream>
using namespace std;
#include<conio.h>
void main()
{
char c;
cout<<”enter character:”;
c=getch();
cout<<”you entered:”<<c;
getch();
}
getche() function:
The letter e in getche stands for echo. The getche() function is used to input single character from the user. When this function is executed, it waits for any key to be pressesd. The function echoes(displays) the character on the screen entered by the user.
This function is defined in the header file conio.h.
SYNTAX
The syntax of getche() function is as follows:
getche();
gets() function
This function is used to enter string value from the user. The input is stored in a string variable. After typing the string from keyboard, the user presses ENTER key and the string is stored in the variable. The null character \0 is automatically entered at the end of string.
SYNTAX
The syntax of gets() function is as follows:
gets(variable);
variable indicates the string variable in which the string is stored.
EXAMPLE
The following statement inputs a string from user and stores it in a string variable str.
cout<<”Enter a string”;
gets(str);
Suppose the user types “Pakistan” on the screen and then presses ENTER key. The string will be stored in str as follows:
Puts() function
The puts() function is used to display string on the screen.it can display a string constant or string variable.
SYNTAX
The syntax of puts() function is as follows:
puts(parameter);
Parameter indicates the string value in which the string is stored. In case of string constant, it is written in double quotes.
EXAMPLE
The following example displays the contents of a string variable str on screen:
Puts(str);
The following example displays a string constant on the screen:
Puts(“programming makes life interesting”);
PROGRAM
# include<iostream>
using namespace std;
#include<conio.h>
void main()
{
char book[50];
cout<<”enter name of your favorite book:”;
gets(book);
cout<<”your favorite book is:”;
puts(book);
getch();
}
The clear screen function (clrscr):
The clrscr function is used to clear the screen. it is an abbreviation of clear screen. When this function is executed, the screen is cleared and the cursor blinks on the top left corner. This function is available in the header file conio.h.
SYNTAX
The syntax of clrscr is as follows:
clrscr(); | http://www.tutorialology.com/cplusplus/basic-input-output/ | CC-MAIN-2017-22 | refinedweb | 1,007 | 64.51 |
Talk:OpenStreetMap is a social activity
Deletion
Brycenesbitt marked this page for deletion with the following reason: non-productive edit wars and unlabeled non-consensus editorial opinion. —M!dgard [ talk | projects | current proposal ] 06:19, 8 May 2015 (UTC)
- I disagree that "OpenStreetMap is a social activity" should be removed, this point of view wasn't covered at wiki before. I'm not sure how deletion proposal will help wiki, please clarify? Xxzme (talk) 06:01, 8 May 2015 (UTC)
- A wiki is a bad place for expressing opinion. Brycenesbitt (talk) 06:07, 8 May 2015 (UTC)
- Then we should revert all of your first edits and pages you create, right? Stub was placed to help users navigate wiki. Xxzme (talk) 06:10, 8 May 2015 (UTC)
- Your behavior and edits have been un-wiki-like. Many of your cleanup edits are good, but they come at a high cost. Please reconsider your own "social activity" here on this wiki. Brycenesbitt (talk) 06:22, 8 May 2015 (UTC)
- Again, topic OpenStreetMap is a social activity wasn't covered at wiki before. Why you think deletion of OpenStreetMap is a social activity stub will help wiki? Xxzme (talk) 06:25, 8 May 2015 (UTC)
- How about if you create the page in a social way. Write it. Post it to a mailing list. Gather feedback and comment from other users. Then, perhaps, mark it as opinion and post it. But really, the wiki is a poor place for expressing your opinion. Brycenesbitt (talk) 15:59, 8 May 2015 (UTC)
- Wiki_Help#Getting_started_with_wiki_editing. Xxzme (talk) 16:52, 8 May 2015 (UTC)
- OpenStreetMap is a social activity is main page in Category:OSM Community and shouldn't be removed, only replaced with better variant. If Brycenesbitt cannot give better look to this stub that's not problem of this page. Xxzme (talk) 06:28, 8 May 2015 (UTC)
- It's only the main page in that category because you placed it there. How is that an argument?
- For what it's worth, I support the deletion. You can start working on a page in your user name space, but please only don't move it to the main namespace, and especially don't link to it from highly visible pages, until it actually has worthwhile content. --Tordanik 08:58, 8 May 2015 (UTC)
- That's not how wiki editing works. Even Steve words were significantly updated over time.
- Yes I placed main page for category as described in Wiki_guidelines#Categories: A single line introduction should be provided for every category which should in general link to an appropriate 'main' page for the subject, ideally of the same name.
- Since you are not putting effort to improve text at this page, I don't see how your opinion about "worthwhile content" should be considered about where this page is located.
- Page was placed as main page for category according wiki guidelines. Yes it was me who did, not you. Xxzme (talk) 09:14, 8 May 2015 (UTC)
- The words "in general" do not mean "always". If the need for such a page does not arise naturally, don't create it. --Tordanik 09:39, 8 May 2015 (UTC)
- I need this page to explain category. I created it. It it clear now for you? Your suggestion is against Wiki_guidelines#Categories. Date to explain why we should remove page that explains Category:OSM Community? Xxzme (talk) 09:44, 8 May 2015 (UTC)
- Proposal: first move the page to your test space until it meets a certain minimum level of quality (it need not be complete, it just needs quality). Then change title to "Editorial by Xxzme: OpenStreetMap is a social activity". Change page URL to "wiki/Editorials/OpenStreetMap is a social activity". Create a space for editorial opinion that does not need to conform to the consensus view. Brycenesbitt (talk) 18:44, 8 May 2015 (UTC)
- What does minimum level of quality even means?
- This page was placed to describe category Category:OSM Community according to Wiki_guidelines#Categories.
- If you cannot improve this page, then there nothing to talk about. This is not my opinion. This is not only my opinion.
- If you see how this page could be improved then do it! Wiki_Help#Getting_started_with_wiki_editing Xxzme (talk) 18:58, 8 May 2015 (UTC)
It's not unreasonable to simply make a start on a page and link it from some places in the hope that others will help improve it. That's a fairly normal wiki approach. However...
You do all these things too quickly and clumsily. The page appears to cover quite a broad sweeping topic area. A matter of principle for the project as a whole. Yet it doesn't do a very good job of explaining what it's about, and you haven't convinced anybody else in the wiki community that this page needs to exist or is worth working on. ...which is a problem because it needs work. It has lots of obvious english errors for a start. Lots of unfinished thoughts. And yet you have linked it from several prominent places.
-- Harry Wood (talk) 00:42, 9 May 2015 (UTC)
- Yes, I wasn't paying attention to the text, but to navigation and cross-links.
- Intent of this article to provide simple interlocutory text about social aspects of OSM with cross-links. Why there community in OSM? Why QA is related to the community? [1] [2].
- It was never intended as in-depth article. There dozens of introductions already (Main Page, Category:Portals) to cover them at single page.
- Many of social aspects directly related to data and data quality.
- It is linked from prominent places because it leads to top level cat [3].
- PeterIto edits were coherent, but how explain them without writing "Introduction to OSM"? How community is related to data quality? How social interaction can improve data? Xxzme (talk) 08:00, 9 May 2015 (UTC)
- Xxzme you're creating a social page in an anti-social way. Please revert your own edits. Brycenesbitt (talk) 15:29, 9 May 2015 (UTC)
- Creating stub is not anti-social. But you can skip this step and compare me with Hitler if you feel comfortable to ask these questions.
- If you ignore need in this page spamming delete proposals instead of improving it - that's not my fault, I was focused on different topic.
- Will you continue deletion proposal spamming or do have ideas how to improve this page? Xxzme (talk) 16:42, 9 May 2015 (UTC)
- I feel this page can be improved by removing the contents, and the links to the page. The subject matter and approach are not a good fit for the wiki. This page is not ready even to be a stub. Work on it somewhere else, and bring it to the community when it shows promise. Brycenesbitt (talk)
- Even [4] this was enough for stub.
- OpenStreetMap is a social activity describes Category:OSM Community according to Wiki_guidelines#Categories,
- No, I don't see how we should vandal pages at wiki and reduce navigation just because Brycenesbitt said it is not good fit for wiki. Xxzme (talk) 19:14, 9 May 2015 (UTC)
- By arguing, you're missing the point. I will no longer interact with you. The original page at Introduction_to_OSM is much better than this one. Brycenesbitt (talk) 19:21, 9 May 2015 (UTC)
So did anyone figure out the purpose of this page yet? I see it's been mostly de-linked everywhere. Do we want to do a rename/redirect/delete?
It seems to me that most of the points, at least towards the top of the page, are advocating (in maybe an overly strong and opinionated way) using changeset comments i.e. not leaving them blank. Maybe this page is best redirected to Good changeset comments.
But the page title implies that it's something more than that, and I think that was Xxzme's intention. But the contents don't cover the broad range of topics the title would imply.
Another option which might make most sense. Move this page to User:Xxzme's user space "User:Xxzme/OpenStreetMap is a social activity" as a personal work in progress for him.
-- Harry Wood (talk) 14:00, 30 July 2015 (UTC) | http://wiki.openstreetmap.org/wiki/Talk:OpenStreetMap_is_a_social_activity | CC-MAIN-2016-44 | refinedweb | 1,379 | 65.73 |
Hey all, I posted a question earlier this week regarding dev-c++ and my inability to keep the output window (#include <iostream>) open long enough to see my program running!
I have already tried the following things and would be grateful for any other suggestions!
1:
(Without typing using namespace std;) \\At the top
std::cout << "Press enter to exit";
std::cin.ignore(std::cin.rdbuf()->in_avail + 1);
return 0;
2:
(Typing using namespace std;) \\At the top
cout << "Press enter to exit";
cin.ignore(cin.rdbuf()->in_avail + 1)
return 0;
3:
#include <cstdio> \\At the top
cout << "Press enter to exit";
getchar();
return 0;
Someone please help! I seem to have tried everything! If anyone knows dev-c++, could you give me a sure fire way of keeping the output window open! Thank you!
(And thanks to the guys or gals who have already suggest ways to help!) | https://www.daniweb.com/programming/software-development/threads/15794/dev-c-premature-closing | CC-MAIN-2016-50 | refinedweb | 149 | 71.14 |
Introduction
I have always been a big fan of all things by Korg, especially their line of hardware touchpad synthesizers, the Kaossilator and current Kaossilator 2. You just turn the little thing on, select a sound, touch the face and it makes music. I wanted to have something similar for my own phone. The result is not quite as fancy as the Korg version: I embed a single sound into my engine and there is no arpeggiator. However, with Android we can use multitouch to support playing chords and multiple events, something the Kaossilator cannot do. Also we are not limited to sample playback. We have the entire arsenal of Csound opcodes to generate sounds on the fly.
Making your own music app with Csound is extremely rewarding and exciting, and you do not have to understand every single aspect of Android app development to get started. You can copy one of the Csound examples or mash up a couple of those, and bootstrap yourself into native Android app development and keep learning as you go. This is how I got started and because I want to help you have as much fun as I did I released my code as open source. Now I am writing this article to take you through my process of development, step by step in detail. You can grab a copy of all the files used in this tutorial by cloning the open source github project at. You can also download a free copy from the Google Play shop to your Android device.
I. Creating the App Code
The Base Activity
To get started please refer to the .pdf document, Csound for Android[1] that comes with the Csound for Android[2] download and follow the setup instructions carefully.
Figure 1. Eclipse IDE showing reference to CsoundAndroid Library.
You should now have a project setup with a reference to the CsoundAndroid library. You will not be able to do anything yet though. You need 3 additional files to help drive your app. To start, you will need to change your app to use a BaseCsoundActivity. Your BaseCsoundActivity is going to handle loading your .csd file from resources. It also handles the OnCreate and OnDestroy app methods. This extends the basic Android Activity class and your actual app code is going to extend this base code.
If you clone my project from GitHub you can get a shortcut by already having these files in place. However, if you want to create your own project from scratch I suggest you use the BaseCsoundActivity from the CsoundExamples that come with CsoundAndroid.
I will describe the code of the BaseCsoundActivity. To begin, we import all the classes we are going to use to load our .csd file and turn it into a string, as well as create our basic Csound object. The first thing we do is create the base Csound Object. We do not actually do anything with it here except create a new instance within the BaseCsoundActivity.
protected CsoundObj csoundObj = new CsoundObj();
Next we will override the basic Activity methods that any Android app needs to implement in order to run. We enable Csound message logging so that we can see what kind of messages we get from Csound. We also re-create an instance of the app from a saved instance if it is backgrounded. This is all pretty normal Android procedure you will find in any app code.
@Override public void onCreate(Bundle savedInstanceState) { csoundObj.setMessageLoggingEnabled(true); super.onCreate(savedInstanceState); }
Next we need to override the
onDestroy() method so that Android knows how to properly close the app. If we do not do this, Csound will continue to run even when the app is shut down and potentially cause problems for other apps. To be a good app citizen, we stop Csound when the app is destroyed.
@Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); csoundObj.stopCsound(); }
The next two methods grab our .csd resource file and turn it into a string. This is not too exciting, only just basic Java. Below we grab the resource file and then add it to a string called
line. This will be passed to csound as the .csd file that is processed by the API. It might seem a bit convoluted but every resource in Android is stored within the binary APK file. The resource files then need to be processed into another state to become a string or other item to use within the app.
protected String getResourceFileAsString(int resId) { StringBuilder str = new StringBuilder(); InputStream is = getResources().openRawResource(resId); BufferedReader r = new BufferedReader(new InputStreamReader(is)); String line; try { while ((line = r.readLine()) != null) { str.append(line).append("\n"); } } catch (IOException ios) {} return str.toString(); }
The following utility method will create a temporary file on disk which is based on the name of our resource. It may seem convoluted, but Csound needs an actual .csd file which has to be temporarily generated to the disk.
protected File createTempFile(String csd) { File f = null; try { f = File.createTempFile("temp", ".csd", this.getCacheDir()); FileOutputStream fos = new FileOutputStream(f); fos.write(csd.getBytes()); fos.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return f; }
A final thing to notice is that you do not need to set the permission to read and write from the file system because we are only using the temp system.
The MainActivity
Now that our BaseCsoundActivity is setup, it is time to put together our MainActivity. You can actually call this activity whatever you want. In my app I only have one Activity deriving from my Base Activity so I call it MainActivity. This is where you are going to setup your view, capture your multitouch events, load your .csd resource and send your multi touch events to your Csound .csd synth. To begin with we are going to import the classes we need for the MainActivity.
import java.io.File; import java.util.Random; import com.magickhack.psychoflute.R; import android.graphics.Color; import android.os.Bundle; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import com.csounds.CsoundObj; import com.csounds.CsoundObjCompletionListener; import com.csounds.valueCacheable.CsoundValueCacheable; import csnd6.CsoundMYFLTArray; import csnd6.controlChannelType;
We import some standard classes here: the Android View library, the touch classes to capture our events and the Csound classes to pass our events as arrays as well as the object completion listener to turn off Csound when interaction is complete and the value cacheable objects to cache our events before sending them to Csound. We also import the R or resource class for our own app so we can access the images and .csd file from the resources folders within the APK.
In addition to these features taken from the multitouch example, I added background color which changes depending upon how fast you move your fingers on the screen, as well as a background image that loads by default when the app starts up.
Next we are going to extend BaseCsoundActivity and implement the necessary interfaces within our MainActivity.
public class MainActivity extends BaseCsoundActivity implements CsoundObjCompletionListener, CsoundValueCacheable
After we create the main activity we will set up the multitouch view and activity variables.
public View multiTouchView; int touchIds[] = new int[4]; float touchX[] = new float[4]; float touchY[] = new float[4]; CsoundMYFLTArray touchXPtr[] = new CsoundMYFLTArray[4]; CsoundMYFLTArray touchYPtr[] = new CsoundMYFLTArray[4];
The view instantiation does not do anything but create a new instance of the the multitouch view class. Then we set up a series of arrays, shown below. The first array is an integer array that holds the IDs of the touch events. The next two arrays are float arrays that will store the raw X and Y data for the multitouch events. Finally we have the Csound float array types which will actually be used to send the data over the channel, translated from the touch id and raw data arrays. Notice the size of these arrays. I set them to 4 so I have a maximum of 4 finger multi touch. Set the number to 10 and you have 10 finger multitouch, but my instruments tend to get too loud with too many fingers so I intentionally limit mine to 4 fingers.
Before we get to the core of the app, we add two more small methods: the
getTouchIdAssignment() method and the
getTouchId(int touchId) method. These methods allow us to grab the touch id by number or to get a default item if the events are still in an initial state. If no id can be found it defaults to -1, which tells the engine no touch has occurred yet.
protected int getTouchIdAssignment() { for(int i = 0; i < touchIds.length; i++) { if(touchIds[i] == -1) { return i; } } return -1; } protected int getTouchId(int touchId) { for(int i = 0; i < touchIds.length; i++) { if(touchIds[i] == touchId) { return i; } } return -1; }
Next we will dive into the core of the app. This is the onCreate method, which is called when the app is started up.
super.onCreate(savedInstanceState); getWindow().setBackgroundDrawableResource(R.drawable.ic_pentagram); csoundObj.enableAccelerometer(MainActivity.this); for(int i = 0; i < touchIds.length; i++) { touchIds[i] = -1; touchX[i] = -1; touchY[i] = -1; } multiTouchView = new View(this);
A few things happen above. First we are recreating the app from a saved state, in case it was backgrounded and returning to foreground active usage. Next we draw the background startup splash image so the user is not just confronted with a blank white screen. I am also enabling the accelerometer so I can pass that data along with the X and Y data to Csound. We do not need extra code to manually send the accelerometer data to our .csd because we have a built-in channel we can hook into from our .csd just by enabling the accelerometer here.
Next we set all touch IDs to -1 to initialize our arrays, so we know we are in an "untouched" state at launch, and finally we attach our multitouch view to the current active view. Then we are ready to start listening for multitouch events, and to do that we are going to use an anonymous OnTouchListener class, shown in the code below.
multiTouchView.setOnTouchListener(new OnTouchListener() { public boolean onTouch(View v, MotionEvent event) { // touch processing code goes here... }); });
All of our multitouch processing code is going to live within this listener's method call. The call to
setOnTouchListener() sets up an instance of the listener, and the listener's
onTouch() method actually captures the touch activity so we can filter for a few different touch and click states. The inner loop is a boolean loop so at the end of processing input we simply return true to exit from the onTouch loop.
In order to handle both touchscreen and mouse based Android devices we are going to use a case statement to filter the actions based on a special action variable that combines both a generic motion event
getAction() method call with an
ACTION_MASK. I will also generate a random object to use to create a random color for my background later.
final int action = event.getAction() & MotionEvent.ACTION_MASK; Random rnd = new Random(); int color = Color.argb(255, rnd.nextInt(256), rnd.nextInt(256), rnd.nextInt(256));
From here we can use this action variable to switch our actions based on the kind of input events shown in the following code.
switch(action) { case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: // handle touch and mouse click code here break; case MotionEvent.ACTION_MOVE: // handle touch and mouse movement break; case MotionEvent.ACTION_POINTER_UP: case MotionEvent.ACTION_UP: // handle code touch touch off and mouse off break; }
The next chunk of code, shown below, is the largest amount of code. We are handling a combination of finger or mouse events touching or clicking the screen and then passing the X and Y coordinates to our .csd.
case MotionEvent.ACTION_DOWN: case MotionEvent.ACTION_POINTER_DOWN: for(int i = 0; i < event.getPointerCount(); i++) { int pointerId = event.getPointerId(i); int id = getTouchId(pointerId); if(id == -1) { id = getTouchIdAssignment(); if(id != -1) { touchIds[id] = pointerId; touchX[id] = event.getX(i) / multiTouchView.getWidth(); touchY[id] = 1 - (event.getY(i) / multiTouchView.getHeight()); if(touchXPtr[id] != null) { touchXPtr[id].SetValue(0, touchX[id]); touchYPtr[id].SetValue(0, touchY[id]); csoundObj.sendScore( String.format("i1.%d 0 -2 %d", id, id) ); multiTouchView.setBackgroundColor((int) (id + id + color)); } } } }
We loop through the pointer count of the event object. First we check for
id == -1 so we know we are in a state of "raw touch". If a touch event was found, but ids have not yet been assigned, then we make the assignment and check again. If the assignment has worked the -1 should be replaced with the new touch id. We grab the X and Y coordinates for the event and then pass them to our running .csd. Then I change the background color of the view using a combination of my random color plus the X and Y variables that were passed to the .csd.
Next we are going to check for a movement event. In this case we do not pass the ids directly to the running .csd but store them in our id array instead, shown below.
case MotionEvent.ACTION_MOVE: for(int i = 0; i < event.getPointerCount(); i++) { int pointerId = event.getPointerId(i); int id = getTouchId(pointerId); if(id != -1) { touchX[id] = event.getX(i) / multiTouchView.getWidth(); touchY[id] = 1 - (event.getY(i) / multiTouchView.getHeight()); } }
We will check again to see that the id is not empty in this case and only add the X and Y to the touchX and touchY arrays. If we have touch ids set from the previous touch event, we need to have a touch event occur first before we can have movement. Finally when the finger or mouse is taken off the screen or in an unclicked state we go through the final case statement logic shown in the code below.
What happens here is that we detect that the interaction is over. If the pointer id is not -1 then we send any events that need to go to Csound before we stop playing. Then I pass the id variables and mix them with the random color to switch the background color according to the event.
case MotionEvent.ACTION_POINTER_UP: case MotionEvent.ACTION_UP: int activePointerIndex = event.getActionIndex(); int pointerId = event.getPointerId(activePointerIndex); int id = getTouchId(pointerId); if(id != -1) { touchIds[id] = -1; csoundObj.sendScore(String.format("i-1.%d 0 0 %d", id, id)); multiTouchView.setBackgroundColor((int) (id + id + color)); }
Below, I set the background color again, just using the random color in order to give a strobing color effect.
multiTouchView.setBackgroundColor(color);
After we escape from the touch event loop we have to do a few more important steps. Below, we set the actual content view to the multitouch view, before we set up the class and create an instance of the object. Here we actually load it into the running view. Then we load the Csound resource and turn it into a temp file to process it into a string. Then we add our cached values and actually start Csound running. Now we just have a couple of helper methods to add to the Java part of our app and it is done.
setContentView(multiTouchView); String csd = getResourceFileAsString(R.raw.multitouch_xy); File f = createTempFile(csd); csoundObj.addValueCacheable(this); csoundObj.startCsound(f);
For this application this method shown below is left empty because the mouse/fingers off part of the event loop already handles this state so we do not need to stop Csound from running here as we might with other kinds of apps. Next we have our methods used for the Csound value cache.
public void csoundObjComplete(CsoundObj csoundObj) {}
The methods below map the input of the touch ids to the Csound control channels, and then handle updating those values. The update from method is blank because we are only sending to Csound on the channel. Nothing is being returned back from Csound to the app.
public void setup(CsoundObj csoundObj) { for(int i = 0; i < touchIds.length; i++) { touchXPtr[i] = csoundObj.getInputChannelPtr( String.format("touch.%d.x", i), controlChannelType.CSOUND_CONTROL_CHANNEL ); touchYPtr[i] = csoundObj.getInputChannelPtr( String.format("touch.%d.y", i), controlChannelType.CSOUND_CONTROL_CHANNEL ); } } public void updateValuesToCsound() { for(int i = 0; i < touchX.length; i++) { touchXPtr[i].SetValue(0, touchX[i]); touchYPtr[i].SetValue(0, touchY[i]); } } public void updateValuesFromCsound() {}
We have one final cleanup method which frees up the channels that were previously cached for all of the touch channels.
public void cleanup() { for(int i = 0; i < touchIds.length; i++) { touchXPtr[i].Clear(); touchXPtr[i] = null; touchYPtr[i].Clear(); touchYPtr[i] = null; } }
That is it for the Java portion of our app. That is quite a lot going on. We could try to add more but to keep things lean and mean we can change the background color without evening having to run a separate thread because Android is handling that property change behind the scenes in an elegant way for us.
II. Developing the Csound Code
CSD Setup
So now that we have our app done, we need a Csound file to receive our channel messages. The
wgflute opcode, being one of my favorites, is a natural one I would choose to receive messages from this app. I used the multitouch .csd example as the basis of my app but then made a bunch of modifications on top of switching the opcode from an oscillator to the physical model. First off, I used the same settings as the example for my audio output.
-o dac -d -b512 -B2048
We are setting up basic audio output to the DAC and then setting a buffer size of 512 and 2048 for software and hardware buffers sizes, giving clean audio output. Next we will setup the Csound header. This is also a standard setting for stereo output.
nchnls=2 0dbfs=1 ksmps=32 sr = 44100 ga1 init 0
We are using a standard sample rate and use
0dbfs for volume control. Note the
ga1 variable. We will use this variable to pass the
wgflute opcode output into a
moogladder filter opcode.
The Opcodes
The largest chunk of our code is used by the flute instrument. Here we map the channels to the control parameters. As above, we could do more, like mapping to the filter to control it from channels, but for now the filter is just there to add grit to the flute sound and has a set resonance and cutoff. Here is the final code for the opcode instrument.
instr 1 itie tival i_instanceNum = p4 S_xName sprintf "touch.%d.x", i_instanceNum S_yName sprintf "touch.%d.y", i_instanceNum kx chnget S_xName ky chnget S_yName kaccelX chnget "accelerometerX" kaccelY chnget "accelerometerY" kenv linsegr 0, .0001, 1, .1, 1, .25, 0 kamp = .5 * kenv kfreq = kx*100 kjet = rnd(900) + ky + kaccelY * 0.001 iatt = 0.1 idetk = 0.1 kngain = 0.005 kvibf = rnd(10000) + ky + kaccelX * 0.001 kvamp = 0.00005 ifn = 1 asig wgflute kamp, kfreq, kjet, iatt, idetk, kngain, kvibf, kvamp, ifn ga1 = ga1 + asig endin
We grab both the X and Y multitouch channels and the accelerometer channels and combine those values with randomly generated values to create a semi-controlled, semi-random instrument. Then we pass this to the simple
moogladder filter to add some analog style grit to the flute sound before it goes to audio output.
instr 2 kcutoff = 6000 kresonance = .2 a1 moogladder ga1, kcutoff, kresonance outs a1, a1 ga1 = 0 endin
We reset the
ga1 variable back to 0 after output. We have a single function table for the
wgflute opcode, and then we setup a very simple score to cause the instrument to play indefinitely.
f1 0 16384 10 1 i2 0 360000
That is the complete process for the .csd portion of the code. Now we can build our touchpad synth app and share it with the world, or even keep it to yourself as a musical "secret weapon" for live performance.
Acknowledgements
Thanks to the talented geniuses who created the Csound Android Native Library. The development of this library represents a major achievement. Software that once required a mainframe level machine to run now runs on even modest inexpensive ubiquitous Android hardware.
References
[1] Victor Lazzarini, Steven Yi and Martin O'Shea, "Csound for Android," in "csound-android." [Online]. Available:. [Accessed January 15, 2014].
[2] Victor Lazzarini, Steven Yi, et. al., "csound-android." [Online]. Available:. [Accessed January 15, 2014].
Additional Links
Eclipse IDE. [Online]. Available:. [Accessed January 15, 2014].
Korg. "Kaossilator 2." [Online] Available:. [Accessed January 15, 2014].
Steven Yi and Victor Lazzarini, "Csound for Android." [Online]. Available:. [Accessed January 15, 2014].
Victor Lazzarini, Steven Yi, et. al., "The Mobile Csound Platform," from ICMC2012_Non-Cochlear Sound, Ljubljana, Slovenia, September 9-14, 2012. [Online]. Available:. [Accessed January 15, 2014]. | http://www.csounds.com/journal/issue19/kaoss_droid.html | CC-MAIN-2016-18 | refinedweb | 3,484 | 65.93 |
Prev
Java Set Experts Index
Headers
Your browser does not support iframes.
Re: JSTL: getting a map's keys
From:
Lew <noone@lewscanon.com>
Newsgroups:
comp.lang.java.programmer
Date:
Fri, 23 Mar 2012 13:50:55 -0700
Message-ID:
<jkinnf$dv8$1@news.albasani.net>
Chris Riesbeck wrote:
Lew wrote:
Chris Riesbeck wrote:
Lew wrote:
Chris Riesbeck wrote:
So I don't see how I can have a class such that in the JSP EL I can call
a method to get all the keys, and also retrieve data with a key using [].
I was thinking along the lines of this incompletely worked-through notion:
public class ContactScreenBacker
{
private final Map<String, Rate> rates = howeverYouSetItUp();
public Map<String, Rate> getRates() { return
Collections.unmodifiableMap(rates); }
public Set<String> getKeys() { return
Collections.unmodifiableSet(rates.getKeys(); }
// ...
}
You should be able to use an EL like '#{thingie.rates["Bill"]}'. I
haven't tried it, but this is what I had in mind.
Yes, that's probably the approach I'll take. Not quite what I'd wanted, but
close enough and I can't see why it shouldn't work.
Let us know how it plays out, please.
--
Lew
Honi soit qui mal y pense.
Generated by PreciseInfo ™
"One can trace Jewish influence in the last revolutionary
explosions in Europe.
An insurrection has taken place against traditions, religion
and property, the destruction of the semitic principle,
the extirpation of the Jewish religion, either under its
Mosaic or Christian form, the natural equality of men and
the annulment of property are proclaimed by the secret
societies which form the provisional government, and men
of the Jewish race are found at the head of each of them.
The People of God . 120121) | https://preciseinfo.org/Convert/Articles_Java/Set_Experts/Java-Set-Experts-120323225055.html | CC-MAIN-2022-33 | refinedweb | 287 | 63.8 |
pytest plugin to check source code with pyflakes
Project description
pytest-flakes
py.test plugin for efficiently checking python source with pyflakes.
Usage
install via:
pip install pytest-flakes
if you then type:
py.test --flakes
every file ending in .py will be discovered and run through pyflakes, starting from the command line arguments.
Simple usage example
Consider you have this code:
# content of module.py import os from os.path import * def some_function(): pass
Running it with pytest-flakes installed shows two issues:
$ py.test -q --flakes F ================================= FAILURES ================================= ______________________________ pyflakes-check ______________________________ /tmp/doc-exec-685/module.py:2: UnusedImport 'os' imported but unused /tmp/doc-exec-685/module.py:3: ImportStarUsed 'from os.path import *' used; unable to detect undefined names 1 failed in 0.00 seconds
These are only two of the many issues that pytest-flakes can find.
Configuring pyflakes options per project and file
You may configure pyflakes-checking options for your project by adding an flakes-ignore entry to your setup.cfg or pytest.ini file like this:
# content of setup.cfg [pytest] flakes-ignore = ImportStarUsed
This would globally prevent complaints about star imports. Rerunning with the above example will now look better:
$ py.test -q --flakes F ================================= FAILURES ================================= _________________ pyflakes-check(ignoring ImportStarUsed) __________________ /tmp/doc-exec-685/module.py:2: UnusedImport 'os' imported but unused 1 failed in 0.00 seconds
But of course we still would want to delete the import os line to have a clean pass.
If you have some files where you want to specifically ignore some errors or warnings you can start a flakes-ignore line with a glob-pattern and a space-separated list of codes:
# content of setup.cfg [pytest] flakes-ignore = *.py UnusedImport doc/conf.py ALL
Ignoring certain lines in files
You can ignore errors per line by appending special comments to them like this:
import sys # noqa app # pragma: no flakes
Running pyflakes checks and no other tests
You can restrict your test run to only perform “flakes” tests and not any other tests by typing:
py.test --flakes -m flakes
This will only run tests that are marked with the “flakes” keyword which is added for the flakes test items added by this plugin.
If you are using pytest < 2.4, then use the following invocation to the same effect:
py.test --flakes -k flakes
Notes
The repository of this plugin is at
For more info on py.test see
The code is partially based on Ronny Pfannschmidt’s pytest-codecheckers plugin and Holger Krekel’s pytest-pep8.
Changes
4.0.5 - 2021-12-02
- Further fixes for deprecations in the upcoming pytest 7.0. [nicoddemus]
4.0.4 - 2021-10-26
- Fix pytest-flakes for deprecations in the upcoming pytest 7.0. [bluetech]
- Fix the pytest-flakes test suite in Python 3.10. [bluetech]
- Replace Travis CI with GitHub Actions. [bluetech]
4.0.3 - 2020-11-27
- Future proof some code against future versions of pytest. [RonnyPfannschmidt]
4.0.2 - 2020-09-18
- Fix calling pytest –flakes directly on an __init__.py file. [akeeman]
4.0.1 - 2020-07-28
- Maintenance of pytest-flakes has moved from fschulze to asmeurer. The repo for pytest-flakes is now at
- Fix test failures. [asmeurer]
- Fix deprecation warnings from pytest. [asmeurer]
- Fix invalid escape sequences. [akeeman]
4.0.0 - 2018-08-01
- Require pytest >= 2.8.0 and remove pytest-cache requirement. Cache is included in pytest since that version. [smarlowucf (Sean Marlow)]
3.0.2 - 2018-05-16
- Fix typo in name of flakes marker. [fschulze]
3.0.1 - 2018-05-16
- Always register flakes marker, not only when the --flakes option is used. [fschulze]
3.0.0 - 2018-05-16
- Drop support for Python 3.3. It still works so far, but isn’t tested anymore. [fschulze]
- Add flakes marker required since pytest 3.1. [fschulze]
- Use pyflakes.api.isPythonFile to detect Python files. This might test more files than before and thus could cause previously uncaught failures. [asmeurer (Aaron Meurer)]
2.0.0 - 2017-05-12
- Dropped support/testing for Python 2.5, 2.6, 3.2. [fschulze]
- Added testing for Python 3.6. [fschulze]
- Fixed some packaging and metadata errors. [fladi (Michael Fladischer), fschulze]
1.0.1 - 2015-09-17
- Compatibility with upcoming pytest. [RonnyPfannschmidt (Ronny Pfannschmidt)]
1.0.0 - 2015-05-01
- Fix issue #6 - support PEP263 for source file encoding. [The-Compiler (Florian Bruhin), fschulze]
- Clarified license to be MIT like pytest-pep8 from which this is derived. [fschulze]
0.2 - 2013-02-11
- Adapt to pytest-2.4.2 using add_marker() API. [fschulze, hpk42 (Holger Krekel)]
- Allow errors to be skipped per line by appending # noqa or # pragma: no flakes [fschulze, silviot (Silvio Tomatis)]
- Python 3.x compatibility. [fschulze, encukou (Petr Viktorin)]
0.1 - 2013-02-04
- Initial release. [fschulze (Florian Schulze)]
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/pytest-flakes/ | CC-MAIN-2022-33 | refinedweb | 836 | 69.48 |
How to configure environment specific parameters with Vue.js and Amplify
When you start a new Vue.js project that needs to interface with APIs running in AWS, there’s a good chance you will have these lines of code:
import Amplify from 'aws-amplify'Amplify.configure({
Auth: {
region: 'us-east-1',
userPoolId: 'xxx',
userPoolWebClientId: 'xxx',
mandatorySignIn: true
}
})
These few lines of code let you use the
aws-amplify library to authenticate the user against a Cognito User Pool and support common flows such as sign-up, sign-in, sign-out, forgotten passwords and change passwords.
But, as you provide your Vue.js project across the different environments —
dev,
test,
staging and
production — these settings have to change.
So instead of hardcoding them, you should inject them via environment variables. And fortunately for us, Vue.js supports the use of
.env files out-of-the-box. However, a caveat that stomped me for a few hours today was that these environment variables need to be prefixed with
VUE_APP_.
This was mentioned in the docs but unless you knew what you were looking for, it wasn’t obvious.
Note that only NODE_ENV, BASE_URL, and variables that start with VUE_APP_ will be statically embedded into the client bundle with webpack.DefinePlugin. It is to avoid accidentally exposing a private key on the machine that could have the same name.
So, you change your code to something like this:
import Amplify from 'aws-amplify'Amplify.configure({
Auth: {
region: process.env.VUE_APP_REGION,
userPoolId: process.env.VUE_APP_USER_POOL_ID,
userPoolWebClientId: process.env.VUE_APP_CLIENT_ID,
mandatorySignIn: true
}
})
And assuming you’re using the AWS Amplify service to deploy this Vue.js application, you need to configure these as environment variables in the Amplify console.
And pull them into a
.env file during the build process. Again, the environment variables in the
.env file needs to be prefixed with
VUE_APP_.
So, in the
amplify.yml file, add these lines to the
build phase, just before the
npm run build step.
- echo "VUE_APP_REGION=$REGION" >> .env
- echo "VUE_APP_USER_POOL_ID=$COGNITO_USER_POOL_ID" >> .env
- echo "VUE_APP_CLIENT_ID=$COGNITO_CLIENT_ID" >> .env
Your amplify.yml will probably look something like this.
version: 1
frontend:
phases:
preBuild:
commands:
- npm ci
build:
commands:
- echo "VUE_APP_REGION=$REGION" >> .env
- echo "VUE_APP_USER_POOL_ID=$COGNITO_USER_POOL_ID" >> .env
- echo "VUE_APP_CLIENT_ID=$COGNITO_CLIENT_ID" >> .env
- npm run build
artifacts:
baseDirectory: dist
files:
- '**/*'
cache:
paths:
- node_modules/**/*
Now they’ll be bundled into the app when Amplify builds and deploys it.
Originally published at on March 2, 2021. | https://theburningmonk.medium.com/how-to-configure-environment-specific-parameters-with-vue-js-and-amplify-1d8016a1a5ed?readmore=1&source=user_profile---------9---------------------------- | CC-MAIN-2021-49 | refinedweb | 404 | 52.46 |
When we build an application in Xcode, part of what happens is that the sources files (
.m and
.h) get turned into an executable. This executable contains the byte code than will run on the CPU, the ARM processor on the iOS device, or the Intel processor on your Mac.
We’ll walk through some of what the compiler does and what’s inside such an executable. There’s more to it than first meets the eye.
Let’s put Xcode aside for this and step into the land of command-line tools. When we build in Xcode, it simply calls a series of tools. Florian discusses how this works in more detail. We’ll call these tools directly and take a look at what they do.
Hopefully this will give you a better understanding of how an executable on iOS or OS X – a so-called Mach-O executable – works and is put together.
xcrun
Some infrastructure first: There’s a command-line tool called
xcrun which we’ll use a lot. It may seem odd, but it’s pretty awesome. This little tool is used to run other tools. Instead of running:
% clang -v
On the Terminal, we’ll use:
% xcrun clang -v
What
xcrun does is to locate
clang and run it with the arguments that follow
clang.
Why would we do this? It may seem pointless. But
xcrun allows us to (1) have multiple versions of Xcode and use the tools from a specific Xcode version, and (2) use the tools for a specific SDK (software development kit). If you happen to have both Xcode 4.5 and Xcode 5, with
xcode-select and
xcrun you can choose to use the tools (and header files, etc.) from the iOS SDK from Xcode 5, or the OS X tools from Xcode 4.5. On most other platforms, that’d be close to impossible. Check out the man pages for
xcrun and
xcode-select for more details. And you can use the developer tools from the command line without installing the Command Line Tools.
Hello World Without an IDE
Back in Terminal, let’s create a folder with a C file in it:
% mkdir ~/Desktop/objcio-command-line % cd !$ % touch helloworld.c
Now edit this file in your favorite text editor – even TextEdit.app will do:
% open -e helloworld.c
Fill in this piece of code:
#include <stdio.h> int main(int argc, char *argv[]) { printf("Hello World!\n"); return 0; }
Save and return to Terminal to run this:
% xcrun clang helloworld.c % ./a.out
You should now see a lovely
Hello World! message on your terminal. You compiled a C program and ran it. All without an IDE. Take a deep breath. Rejoice.
What did we just do here? We compiled
helloworld.c into a Mach-O binary called
a.out. That is the default name the compiler will use unless we specify something else.
How did this binary get generated? There are multiple pieces to look at and understand. We’ll look at the compiler first.
Hello World and the Compiler
The compiler of choice nowadays is
clang (pronounced /klæŋ/). Chris writes in more detail about the compiler.
Briefly put, the compiler will process the
helloworld.c input file and produce the executable
a.out. This processing consist of multiple steps/stages. What we just did is run all of them in succession:
Preprocessing
- Tokenization
- Macro expansion
#includeexpansion
Parsing and Semantic Analysis
- Translates preprocessor tokens into a parse tree
- Applies semantic analysis to the parse tree
- Outputs an Abstract Syntax Tree (AST)
Code Generation and Optimization
- Translates an AST into low-level intermediate code (LLVM IR)
- Responsible for optimizing the generated code
- target-specific code generation
- Outputs assembly
Assembler
- Translates assembly code into a target object file
Linker
- Merges multiple object files into an executable (or a dynamic library)
Let’s see how these steps look for our simple example.
Preprocessing
The first thing the compiler will do is preprocess the file. We can tell clang to show us what it looks like if we stop after that step:
% xcrun clang -E helloworld.c
Wow. That will output 413 lines. Let’s open that in an editor to see what’s going on:
% xcrun clang -E helloworld.c | open -f
At the very top you’ll see lots and lots of lines starting with a
# (pronounced ‘hash’). These are so-called linemarker statements that tell us which file the following lines are from. We need this. If you look at the
helloworld.c file again, you’ll see that the first line is:
#include <stdio.h>
We have all used
#include and
#import before. What it does is to tell the preprocessor to insert the content of the file
stdio.h where the
#include statement was. This is a recursive process: The
stdio.h header file in turn includes other files.
Since there’s a lot of recursive insertion going on, we need to be able to keep track of where the lines in the resulting source originate from. To do this, the preprocessor inserts a linemarker beginning with a
# whenever the origin changes. The number following the
# is the line number followed by the name of the file. The numbers at the very end of the line are flags indicating the start of a new file (1), returning to a file (2), that the following is from a system header (3), or that the file is to be treated as wrapped in an
extern"C" block.
If you scroll to the very end of the output, you’ll find our
helloworld.c code:
# 2 "helloworld.c" 2 int main(int argc, char *argv[]) { printf("Hello World!\n"); return 0; }
In Xcode, you can look at the preprocessor output of any file by selecting Product -> Perform Action -> Preprocess. Note that it takes a few seconds for the Editor to load the preprocessed file – it’ll most likely be close to 100,000 lines long.
Compilation
Next up: parsing and code generation. We can tell
clang to output the resulting assembly code like so:
% xcrun clang -S -o - helloworld.c | open -f
Let’s take a look at the output. First we’ll notice how some lines start with a dot
.. These are assembler directives. The other ones are actual x86_64 assembly. Finally there are labels, which are similar to labels in C.
Let’s start with the first three lines:
.section __TEXT,__text,regular,pure_instructions .globl _main .align 4, 0x90
These three lines are assembler directives, not assembly code. The
.section directive specifies into which section the following will go. More about sections in a bit.
Next, the
.globl directive specifies that
_main is an external symbol. This is our
main() function. It needs to be visible outside our binary because the system needs to call it to run the executable.
The
.align directive specifies the alignment of what follows. In our case, the following code will be 16 (2^4) byte aligned and padded with
0x90 if needed.
Next up is the preamble for the main function:
_main: ## @main .cfi_startproc ## BB#0: pushq %rbp Ltmp2: .cfi_def_cfa_offset 16 Ltmp3: .cfi_offset %rbp, -16 movq %rsp, %rbp Ltmp4: .cfi_def_cfa_register %rbp subq $32, %rsp
This part has a bunch of labels that work the same way as C labels do. They are symbolic references to certain parts of the assembly code. First is the actual start of our function
_main. This is also the symbol that is exported. The binary will hence have a reference to this position.
The
.cfi_startproc directive is used at the beginning of most functions. CFI is short for Call Frame Information. A frame corresponds loosely to a function. When you use the debugger and step in or step out, you’re actually stepping in/out of call frames. In C code, functions have their own call frames, but other things can too. The
.cfi_startproc directive gives the function an entry into
.eh_frame, which contains unwind information – this is how exception can unwind the call frame stack. The directive will also emit architecture-dependent instructions for CFI. It’s matched by a corresponding
.cfi_endproc further down in the output to mark the end of our
main() function.
Next, there’s another label
## BB#0: and then, finally, the first assembly code:
pushq %rbp. This is where things get interesting. On OS X, we have x86_64 code, and for this architecture there’s a so-called application binary interface (ABI) that specifies how function calls work at the assembly code level. Part of this ABI specifies that the
rbp register (base pointer register) must be preserved across function calls. It’s the main function’s responsibility to make sure the
rbp register has the same value once the function returns.
pushq %rbp pushes its value onto the stack so that we can pop it later.
Next, two more CFI directives:
.cfi_def_cfa_offset 16 and
.cfi_offset %rbp, -16. Again, these will output information related to generating call frame unwinding information and debug information. We’re changing the stack and the base pointer and these two basically tell the debugger where things are – or rather, they’ll cause information to be output which the debugger can later use to find its way.
Now,
movq %rsp, %rbp will allow us to put local variables onto the stack.
subq $32, %rsp moves the stack pointer by 32 bytes, which the function can then use. We’re first storing the old stack pointer in
rbp and using that as a base for our local variables, then updating the stack pointer to past the part that we’ll use.
Next, we’ll call
printf():
leaq L_.str(%rip), %rax movl $0, -4(%rbp) movl %edi, -8(%rbp) movq %rsi, -16(%rbp) movq %rax, %rdi movb $0, %al callq _printf
First,
leaq loads the pointer to
L_.str into the
rax register. Note how the
L_.str label is defined further down in the assembly code. This is our C string
"Hello World!\n". The
edi and
rsi registers hold the first and second function arguments. Since we’ll call another function, we first need to store their current values. That’s what we’ll use the 32 bytes based off
rbp we just reserved for. First a 32-bit 0, then the 32-bit value of the
edi register (which holds
argc), then the 64-bit value of the
rsi register (which holds
argv). We’re not using those values later, but since the compiler is running without optimizations, it’ll store them anyway.
Now we’ll put the first function argument for
printf(),
rax, into the first function argument register
edi. The
printf() function is a variadic function. The ABI-calling convention specifies that the number of vector registers used to hold arguments need to be stored in the
al register. In our case it’s 0. Finally,
callq calls the
printf() function:
movl $0, %ecx movl %eax, -20(%rbp) ## 4-byte Spill movl %ecx, %eax
This sets the
ecx register to 0, saves (spills) the
eax register onto the stack, then copies the 0 values in
ecx into
eax. The ABI specifies that
eax will hold the return value of a function, and our
main() function returns 0:
addq $32, %rsp popq %rbp ret .cfi_endproc
Since we’re done, we’ll restore the stack pointer by shifting the stack pointer
rsp back 32 bytes to undo the effect of
subq $32, %rsp from above. Finally, we’ll pop the value of
rbp we’d stored earlier and then return to the caller with
ret, which will read the return address off the stack. The
.cfi_endproc balances the
.cfi_startproc directive.
Next up is the output for our string literal
"Hello World!\n":
.section __TEXT,__cstring,cstring_literals L_.str: ## @.str .asciz "Hello World!\n"
Again, the
.section directive specifies which section the following needs to go into. The
L_.str label allows the actual code to get a pointer to the string literal. The
.asciz directive tells the assembler to output a 0-terminated string literal.
This starts a new section
__TEXT __cstring. This section contains C strings:
L_.str: ## @.str .asciz "Hello World!\n"
And these two lines create a null-terminated string. Note how
L_.str is the name used further up to access the string.
The final
.subsections_via_symbols directive is used by the static link editor.
More information about assembler directives can be found in Apple’s OS X Assembler Reference. The AMD 64 website has documentation on the application binary interface for x86_64. It also has a Gentle Introduction to x86-64 Assembly.
Again, Xcode lets you review the assembly output of any file by selecting Product -> Perform Action -> Assemble.
Assembler
The assembler, simply put, converts the (human-readable) assembly code into machine code. It creates a target object file, often simply called object file. These files have a
.o file ending. If you build your app with Xcode, you’ll find these object files inside the
Objects-normal folder inside the derived data directory of your project.
Linker
We’ll talk a bit more about the linker later. But simply put, the linker will resolve symbols between object files and libraries. What does that mean? Recall the
callq _printf
statement.
printf() is a function in the libc library. Somehow, the final executable needs to be able to know where in memory the
printf() is, i.e. what the address of the
_printf symbol is. The linker takes all object files (in our case, only one) and the libraries (in our case, implicitly libc) and resolves any unknown symbols (in our case, the
_printf). It then encodes into the final executable that this symbol can be found in libc, and the linker then outputs the final executable that can be run:
a.out.
Sections
As we mentioned above, there’s something called sections. An executable will have multiple sections, i.e. parts. Different parts of the executable will each go into their own section, and each section will in turn go inside a segment. This is true for our trivial app, but also for the binary of a full-blown app.
Let’s take a look at the sections of our
a.out binary. We can use the
size tool to do that:
% xcrun size -x -l -m a.out Segment __PAGEZERO: 0x100000000 (vmaddr 0x0 fileoff 0) Segment __TEXT: 0x1000 (vmaddr 0x100000000 fileoff 0) Section __text: 0x37 (addr 0x100000f30 offset 3888) Section __stubs: 0x6 (addr 0x100000f68 offset 3944) Section __stub_helper: 0x1a (addr 0x100000f70 offset 3952) Section __cstring: 0xe (addr 0x100000f8a offset 3978) Section __unwind_info: 0x48 (addr 0x100000f98 offset 3992) Section __eh_frame: 0x18 (addr 0x100000fe0 offset 4064) total 0xc5 Segment __DATA: 0x1000 (vmaddr 0x100001000 fileoff 4096) Section __nl_symbol_ptr: 0x10 (addr 0x100001000 offset 4096) Section __la_symbol_ptr: 0x8 (addr 0x100001010 offset 4112) total 0x18 Segment __LINKEDIT: 0x1000 (vmaddr 0x100002000 fileoff 8192) total 0x100003000
Our
a.out file has four segments. Some of these have sections.
When we run an executable, the VM (virtual memory) system maps the segments into the address space (i.e. into memory) of the process. Mapping is very different in nature, but if you’re unfamiliar with the VM system, simply assume that the VM loads the entire executable into memory – even though that’s not what’s really happening. The VM pulls some tricks to avoid having to do so.
When the VM system does this mapping, segments and sections are mapped with different properties, namely different permissions.
The
__TEXT segment contains our code to be run. It’s mapped as read-only and executable. The process is allowed to execute the code, but not to modify it. The code can not alter itself, and these mapped pages can therefore never become dirty.
The
__DATA segment is mapped read/write but non-executable. It contains values that need to be updated.
The first segment is
__PAGEZERO. It’s 4GB large. Those 4GB are not actually in the file, but the file specifies that the first 4GB of the process’ address space will be mapped as non-executable, non-writable, non-readable. This is why you’ll get an
EXC_BAD_ACCESS when reading from or writing to a
NULL pointer, or some other value that’s (relatively) small. It’s the operating system trying to prevent you from causing havoc.
Within segments, there are sections. These contain distinct parts of the executable. In the
__TEXT segment, the
__text section contains the compiled machine code.
__stubs and
__stub_helper are used for the dynamic linker (
dyld). This allows for lazily linking in dynamically linked code.
__const (which we don’t have in our example) are constants, and similarly
__cstring contains the literal string constants of the executable (quoted strings in source code).
The
__DATA segment contains read/write data. In our case we only have
__nl_symbol_ptr and
__la_symbol_ptr, which are non-lazy and lazy symbol pointers, respectively. The lazy symbol pointers are used for so-called undefined functions called by the executable, i.e. functions that are not within the executable itself. They’re lazily resolved. The non-lazy symbol pointers are resolved when the executable is loaded.
Other common sections in the
__DATA segment are
__const, which will contain constant data which needs relocation. An example is
char * const p = "foo"; – the data pointed to by
p is not constant. The
__bss section contains uninitialized static variables such as
static int a; – the ANSI C standard specifies that static variables must be set to zero. But they can be changed at run time. The
__common section contains uninitialized external globals, similar to
static variables. An example would be
int a; outside a function block. Finally,
__dyld is a placeholder section, used by the dynamic linker.
Apple’s OS X Assembler Reference has more information about some of the section types.
Section Content
We can inspect the content of a section with
otool(1) like so:
% xcrun otool -s __TEXT __text a.out a.out: (__TEXT,__text) section 0000000100000f30 55 48 89 e5 48 83 ec 20 48 8d 05 4b 00 00 00 c7 0000000100000f40 45 fc 00 00 00 00 89 7d f8 48 89 75 f0 48 89 c7 0000000100000f50 b0 00 e8 11 00 00 00 b9 00 00 00 00 89 45 ec 89 0000000100000f60 c8 48 83 c4 20 5d c3
This is the code of our app. Since
-s __TEXT __text is very common,
otool has a shortcut to it with the
-t argument. We can even look at the disassembled code by adding
-v:
% xcrun otool -v -t a.out a.out: (__TEXT,__text) section _main: 0000000100000f30 pushq %rbp 0000000100000f31 movq %rsp, %rbp 0000000100000f34 subq $0x20, %rsp 0000000100000f38 leaq 0x4b(%rip), %rax 0000000100000f3f movl $0x0, 0xfffffffffffffffc(%rbp) 0000000100000f46 movl %edi, 0xfffffffffffffff8(%rbp) 0000000100000f49 movq %rsi, 0xfffffffffffffff0(%rbp) 0000000100000f4d movq %rax, %rdi 0000000100000f50 movb $0x0, %al 0000000100000f52 callq 0x100000f68 0000000100000f57 movl $0x0, %ecx 0000000100000f5c movl %eax, 0xffffffffffffffec(%rbp) 0000000100000f5f movl %ecx, %eax 0000000100000f61 addq $0x20, %rsp 0000000100000f65 popq %rbp 0000000100000f66 ret
This is the same stuff, this time disassembled. It should look familiar – it’s what we looked at a bit further back when compiling the code. The only difference is that we don’t have any of the assembler directives in the code anymore; this is the bare binary executable.
In a similar fashion, we can look at other sections:
% xcrun otool -v -s __TEXT __cstring a.out a.out: Contents of (__TEXT,__cstring) section 0x0000000100000f8a Hello World!\n
Or:
% xcrun otool -v -s __TEXT __eh_frame a.out a.out: Contents of (__TEXT,__eh_frame) section 0000000100000fe0 14 00 00 00 00 00 00 00 01 7a 52 00 01 78 10 01 0000000100000ff0 10 0c 07 08 90 01 00 00
Side Note on Performance
On a side note: The
__DATA and
__TEXT segments have performance implications. If you have a very large binary, you might want to check out Apple’s documentation on Code Size Performance Guidelines. Moving data into the
__TEXT segment is beneficial, because those pages are never dirty.
Arbitrary Sections
You can add arbitrary data as a section to your executable with the
-sectcreate linker flag. This is how you’d add a Info.plist to a single file executable. The Info.plist data needs to go into a
__info_plist section of the
__TEXT segment. You’d pass
-sectcreate segname sectname file to the linker by passing
-Wl,-sectcreate,__TEXT,__info_plist,path/to/Info.plist
to clang. Similarly,
-sectalign specifies the alignment. If you’re adding an entirely new segment, check out
-segprot to specify the protection (read/write/executable) of the segment. These are all documented in the main page for the linker, i.e.
ld(1).
You can get to sections using the functions defined in
/usr/include/mach-o/getsect.h, namely
getsectdata(), which will give you a pointer to the sections data and return its length by reference.
Mach-O
Executables on OS X and iOS are Mach-O executables:
% file a.out a.out: Mach-O 64-bit executable x86_64
This is true for GUI applications too:
% file /Applications/Preview.app/Contents/MacOS/Preview /Applications/Preview.app/Contents/MacOS/Preview: Mach-O 64-bit executable x86_64
Apple has detailed information about the Mach-O file format.
We can use
otool(1) to peek into the executable’s Mach header. It specifies what this file is and how it’s to be loaded. We’ll use the
-h flag to print the header information:
% otool -v -h a.out a.out: Mach header magic cputype cpusubtype caps filetype ncmds sizeofcmds flags MH_MAGIC_64 X86_64 ALL LIB64 EXECUTE 16 1296 NOUNDEFS DYLDLINK TWOLEVEL PIE
The
cputype and
cpusubtype specify the target architecture this executable can run on. The
ncmds and
sizeofcmds are the load commands which we can look at with the
-l argument:
% otool -v -l a.out | open -f a.out: Load command 0 cmd LC_SEGMENT_64 cmdsize 72 segname __PAGEZERO vmaddr 0x0000000000000000 vmsize 0x0000000100000000 ...
The load commands specify the logical structure of the file and its layout in virtual memory. Most of the information
otool prints out is derived from these load commands. Looking at the
Load command 1 part, we find
initprot r-x, which specifies the protection mentioned above: read-only (no-write) and executable.
For each segment and each section within a segment, the load command specifies where in memory it should end up, and with what protection, etc. Here’s the output for the
__TEXT __text section:
Section sectname __text segname __TEXT addr 0x0000000100000f30 size 0x0000000000000037 offset 3888 align 2^4 (16) reloff 0 nreloc 0 type S_REGULAR attributes PURE_INSTRUCTIONS SOME_INSTRUCTIONS reserved1 0 reserved2 0
Our code will end up in memory at 0x100000f30. Its offset in the file is 3888. If you look at the disassembly output from before of
xcrun otool -v -t a.out, you’ll see that the code is, in fact, at 0x100000f30.
We can also take a look at which dynamic libraries the executable is using:
% otool -v -L a.out a.out: /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 169.3.0) time stamp 2 Thu Jan 1 01:00:02 1970
This is where our executable will find the
_printf symbol it’s using.
A More Complex Sample
Let’s look at a slightly more complex sample with three files:
Foo.h:
#import <Foundation/Foundation.h> @interface Foo : NSObject - (void)run; @end
Foo.m:
#import "Foo.h" @implementation Foo - (void)run { NSLog(@"%@", NSFullUserName()); } @end
helloworld.m:
#import "Foo.h" int main(int argc, char *argv[]) { @autoreleasepool { Foo *foo = [[Foo alloc] init]; [foo run]; return 0; } }
Compiling Multiple Files
In this sample, we have more than one file. We therefore need to tell clang to first generate object files for each input file:
% xcrun clang -c Foo.m % xcrun clang -c helloworld.m
We’re never compiling the header file. Its purpose is simply to share code between the implementation files which do get compiled. Both
Foo.m and
helloworld.m pull in the content of the
Foo.h through the
#import statement.
We end up with two object files:
% file helloworld.o Foo.o helloworld.o: Mach-O 64-bit object x86_64 Foo.o: Mach-O 64-bit object x86_64
In order to generate an executable, we need to link these two object files and the Foundation framework with each other:
xcrun clang helloworld.o Foo.o -Wl,`xcrun --show-sdk-path`/System/Library/Frameworks/Foundation.framework/Foundation
We can now run our code:
% ./a.out 2013-11-03 18:03:03.386 a.out[8302:303] Daniel Eggert
Symbols and Linking
Our small app was put together from two object files. The
Foo.o object file contains the implementation of the
Foo class, and the
helloworld.o object file contains the
main() function and calls/uses the
Foo class.
Furthermore, both of these use the Foundation framework. The
helloworld.o object file uses it for the autorelease pool, and it indirectly uses the Objective-C runtime in form of the
libobjc.dylib. It needs the runtime functions to make message calls. This is similar to the
Foo.o object file.
All of these are represented as so-called symbols. We can think of a symbol as something that’ll be a pointer once the app is running, although its nature is slightly different.
Each function, global variable, class, etc. that is defined or used results in a symbol. When we link object files into an executable, the linker (
ld(1)) resolves symbols as needed between object files and dynamic libraries.
Executables and object files have a symbol table that specify their symbols. If we take a look at the
helloworld.o object file with the
nm(1) tool, we get this:
% xcrun nm -nm helloworld.o (undefined) external _OBJC_CLASS_$_Foo 0000000000000000 (__TEXT,__text) external _main (undefined) external _objc_autoreleasePoolPop (undefined) external _objc_autoreleasePoolPush (undefined) external _objc_msgSend (undefined) external _objc_msgSend_fixup 0000000000000088 (__TEXT,__objc_methname) non-external L_OBJC_METH_VAR_NAME_ 000000000000008e (__TEXT,__objc_methname) non-external L_OBJC_METH_VAR_NAME_1 0000000000000093 (__TEXT,__objc_methname) non-external L_OBJC_METH_VAR_NAME_2 00000000000000a0 (__DATA,__objc_msgrefs) weak private external l_objc_msgSend_fixup_alloc 00000000000000e8 (__TEXT,__eh_frame) non-external EH_frame0 0000000000000100 (__TEXT,__eh_frame) external _main.eh
These are all symbols of that file.
_OBJC_CLASS_$_Foo is the symbol as the
Foo Objective-C class. It’s an undefined, external symbol of the
Foo class. External means it’s not private to this object file, as opposed to
non-external symbols which are private to the particular object file. Our
helloworld.o object file references the class
Foo, but it doesn’t implement it. Hence, its symbol table ends up having an entry marked as undefined.
Next, the
_main symbol for the
main() function is also external because it needs to be visible in order to get called. It, however, is implemented in
helloworld.o as well, and resides at address 0 and needs to go into the
__TEXT,__text section. Then there are four Objective-C runtime functions. These are also undefined and need to be resolved by the linker.
If we turn toward the
Foo.o object file, we get this output:
% xcrun nm -nm Foo.o 0000000000000000 (__TEXT,__text) non-external -[Foo run] (undefined) external _NSFullUserName (undefined) external _NSLog (undefined) external _OBJC_CLASS_$_NSObject (undefined) external _OBJC_METACLASS_$_NSObject (undefined) external ___CFConstantStringClassReference (undefined) external __objc_empty_cache (undefined) external __objc_empty_vtable 000000000000002f (__TEXT,__cstring) non-external l_.str 0000000000000060 (__TEXT,__objc_classname) non-external L_OBJC_CLASS_NAME_ 0000000000000068 (__DATA,__objc_const) non-external l_OBJC_METACLASS_RO_$_Foo 00000000000000b0 (__DATA,__objc_const) non-external l_OBJC_$_INSTANCE_METHODS_Foo 00000000000000d0 (__DATA,__objc_const) non-external l_OBJC_CLASS_RO_$_Foo 0000000000000118 (__DATA,__objc_data) external _OBJC_METACLASS_$_Foo 0000000000000140 (__DATA,__objc_data) external _OBJC_CLASS_$_Foo 0000000000000168 (__TEXT,__objc_methname) non-external L_OBJC_METH_VAR_NAME_ 000000000000016c (__TEXT,__objc_methtype) non-external L_OBJC_METH_VAR_TYPE_ 00000000000001a8 (__TEXT,__eh_frame) non-external EH_frame0 00000000000001c0 (__TEXT,__eh_frame) non-external -[Foo run].eh
The fifth-to-last line shows that
_OBJC_CLASS_$_Foo is defined and external to
Foo.o – it has this class’s implementation.
Foo.o also has undefined symbols. First and foremost are the symbols for
NSFullUserName(),
NSLog(), and
NSObject that we’re using.
When we link these two object files and the Foundation framework (which is a dynamic library), the linker tries to resolve all undefined symbols. It can resolve
_OBJC_CLASS_$_Foo that way. For the others, it will need to use the Foundation framework.
When the linker resolves a symbol through a dynamic library (in our case, the Foundation framework), it will record inside the final linked image that the symbol will be resolved with that dynamic library. The linker records that the output file depends on that particular dynamic library, and what the path of it is. That’s what happens with the
_NSFullUserName,
_NSLog,
_OBJC_CLASS_$_NSObject,
_objc_autoreleasePoolPop, etc. symbols in our case.
We can look at the symbol table of the final executable
a.out and see how the linker resolved all the symbols:
% xcrun nm -nm a.out (undefined) external _NSFullUserName (from Foundation) (undefined) external _NSLog (from Foundation) (undefined) external _OBJC_CLASS_$_NSObject (from CoreFoundation) (undefined) external _OBJC_METACLASS_$_NSObject (from CoreFoundation) (undefined) external ___CFConstantStringClassReference (from CoreFoundation) (undefined) external __objc_empty_cache (from libobjc) (undefined) external __objc_empty_vtable (from libobjc) (undefined) external _objc_autoreleasePoolPop (from libobjc) (undefined) external _objc_autoreleasePoolPush (from libobjc) (undefined) external _objc_msgSend (from libobjc) (undefined) external _objc_msgSend_fixup (from libobjc) (undefined) external dyld_stub_binder (from libSystem) 0000000100000000 (__TEXT,__text) [referenced dynamically] external __mh_execute_header 0000000100000e50 (__TEXT,__text) external _main 0000000100000ed0 (__TEXT,__text) non-external -[Foo run] 0000000100001128 (__DATA,__objc_data) external _OBJC_METACLASS_$_Foo 0000000100001150 (__DATA,__objc_data) external _OBJC_CLASS_$_Foo
We see that all the Foundation and Objective-C runtime symbols are still undefined, but the symbol table now has information about how to resolve them, i.e. in which dynamic library they’re to be found.
The executable also knows where to find these libraries:
% xcrun otool -L a.out a.out: /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation (compatibility version 300.0.0, current version 1056.0.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1197.1.1) /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation (compatibility version 150.0.0, current version 855.11.0) /usr/lib/libobjc.A.dylib (compatibility version 1.0.0, current version 228.0.0)
These undefined symbols are resolved by the dynamic linker
dyld(1) at runtime. When we run the executable,
dyld will make sure that
_NSFullUserName, etc. point to their implementation inside Foundation, etc.
We can run
nm(1) against Foundation and check that these symbols are, in fact, defined there:
% xcrun nm -nm `xcrun --show-sdk-path`/System/Library/Frameworks/Foundation.framework/Foundation | grep NSFullUserName 0000000000007f3e (__TEXT,__text) external _NSFullUserName
The Dynamic Link Editor
There are a few environment variables that can be useful to see what
dyld is up to. First and foremost,
DYLD_PRINT_LIBRARIES. If set,
dyld will print out what libraries are loaded:
% (export DYLD_PRINT_LIBRARIES=; ./a.out ) dyld: loaded: /Users/deggert/Desktop/command_line/./a.out dyld: loaded: /System/Library/Frameworks/Foundation.framework/Versions/C/Foundation dyld: loaded: /usr/lib/libSystem.B.dylib dyld: loaded: /System/Library/Frameworks/CoreFoundation.framework/Versions/A/CoreFoundation dyld: loaded: /usr/lib/libobjc.A.dylib dyld: loaded: /usr/lib/libauto.dylib [...]
This will show you all seventy dynamic libraries that get loaded as part of loading Foundation. That’s because Foundation depends on other dynamic libraries, which, in turn, depend on others, and so forth. You can run
% xcrun otool -L `xcrun --show-sdk-path`/System/Library/Frameworks/Foundation.framework/Foundation
to see a list of the fifteen dynamic libraries that Foundation uses.
The dyld’s Shared Cache
When you’re building a real-world application, you’ll be linking against various frameworks. And these in turn will use countless other frameworks and dynamic libraries. The list of all dynamic libraries that need to get loaded gets large quickly. And the list of interdependent symbols even more so. There will be thousands of symbols to resolve. This works takes a long time: several seconds.
In order to shortcut this process, the dynamic linker on OS X and iOS uses a shared cache that lives inside
/var/db/dyld/. For each architecture, the OS has a single file that contains almost all dynamic libraries already linked together into a single file with their interdependent symbols resolved. When a Mach-O file (an executable or a library) is loaded, the dynamic linker will first check if it’s inside this shared cache image, and if so, use it from the shared cache. Each process has this dyld shared cache mapped into its address space already. This method dramatically improves launch time on OS X and iOS. | https://www.objc.io/issues/6-build-tools/mach-o-executables/ | CC-MAIN-2017-26 | refinedweb | 5,414 | 57.77 |
Hi everyone
First of all, I’m sorry if this has been asked or is in the wrong place but I couldn’t find quite what I’m looking for yet
What I want to do is:
Processing sends value to serial on mouse click
Arduino reads value and moves servo forwards
Processing sends new value to tell Arduino left click has been released
Arduino stops moving servo
So far I have the processing code working fine, but how do I move the servo forward 1 degree at a time until the serial value changes ?
This is my code so far (jut to move when clicked atm, base is one of the servo’s)
#include <Servo.h> Servo base; Servo arm; Servo elbow; int pos = (base.read() +1); int SerialValue = 0; void setup(){ base.attach(9); arm.attach(10); elbow.attach(11); Serial.begin(115200); base.write(90); arm.write(90); elbow.write(90); } void loop() { SerialValue = Serial.read(); if (SerialValue == 104){ base.write(pos +1); } }
Thanks in advance
| https://forum.arduino.cc/t/servo-move-at-mouse-click-with-processing/21674 | CC-MAIN-2021-49 | refinedweb | 169 | 58.72 |
> What do you think about doing this only if FS_SAFE is also set,> so for instance at first only FUSE would allow itself to be> made user-mountable?> > A safe thing to do, or overly intrusive?It goes somewhat against the "no policy in kernel" policy ;). I thinkthe warning in the documentation should be enough to make sysadminsthink twice before doing anything foolish:> +Care should be taken when enabling this, since most> +filesystems haven't been designed with unprivileged mounting> +in mind.> +BTW, filesystems like 'proc' and 'sysfs' should also be safe, althoughthe only use for them being marked safe is if the users are allowed toumount them from their private namespace (otherwise a 'mount --bind'has the same effect as a new mount).Thanks,Miklos | http://lkml.org/lkml/2008/1/21/287 | CC-MAIN-2017-51 | refinedweb | 126 | 55.58 |
Opening another timeline crashes Premierefunkbomb May 30, 2011 11:15 AM
I started a new project in CS5.5, added elements to timelines, then exported via XML. Then I used PluralEyes to sync up the few timelines that needed audio sync: run the XML through the external program, and re-import the resulting XML files as new sequences. Now, whenever I try to load an original, non-PluralEyes-synced sequence, Premiere crashes instantly.
This is a serious issue. I have lost all the work I put onto those previous sequences and can't access them at all. At first I was hopeful that the crashes would stop with 5.5 (but who was I kidding).
Crashed thread 14:
14 com.adobe.AdobePremierePro 0x0000000100003540 (anonymous namespace)::CallStartupFramework(int, char const* const*) + 288
Whatever that means.
1. Re: Opening another timeline crashes Premierethe_wine_snob May 30, 2011 11:43 AM (in response to funkbomb)
What platform are you running PrPro CS 5.5 on?
Hunt
2. Re: Opening another timeline crashes Premierefunkbomb May 30, 2011 11:59 AM (in response to the_wine_snob)
OS X 10.6.7
3. Re: Opening another timeline crashes Premierefunkbomb May 30, 2011 9:03 PM (in response to funkbomb)
Forget it. I'm going back to CS5. Clearly 5.5 is not ready for primetime.
4. Re: Opening another timeline crashes PremiereJohn T Smith May 30, 2011 9:17 PM (in response to funkbomb)
5. Re: Opening another timeline crashes Premieredkitsov May 31, 2011 9:29 AM (in response to funkbomb)
Just in case you are using a cineform codec, there is an issue currently with multiple sequences in PPro and a cineform codec. I had a similar issue that was fixed by changing sequence settings so that they are not handled by cineform RT engine.
6. Re: Opening another timeline crashes Premierefunkbomb May 31, 2011 12:28 PM (in response to funkbomb)
You are right, it's Cineform's new Neo version. It's happening in CS5 as well.
7. Re: Opening another timeline crashes Premieredkitsov May 31, 2011 1:05 PM (in response to funkbomb)
Easy fix. Create a new sequence and choose some other preset (not a cineform one (as a matter of fact I have removed all of the cineform presets from my Adobe presees folders, as well as CFRT plugin from plugins directory))
Then make this settings:
NB! Pay special attention to Video Previews Section of the settings tab.
After that copy all of your clips from your existing cineform preset sequences into a new sequence you have created, you should have no more crushes and no more issues with titles. Apparently there is a bug in SDK and cineform people are aware and working on it.
All of your first light settings will work just fine too. As a matter of fact you will be surprized how much more responsive your PPro will become and as a matter of fact Mercury Playback and rendering of the effects will be restored. As of now, when using cineform real time playback plug in inside the PPro, Mercury Playback and Effects become broken
8. Re: Opening another timeline crashes PremiereJeff Bellune May 31, 2011 12:56 PM (in response to funkbomb)
[Off-topic posts deleted] | https://forums.adobe.com/thread/858493 | CC-MAIN-2018-09 | refinedweb | 540 | 70.43 |
The Must Know Checklist For DevOps & Site Reliability Engineers
Disclaimer: This work was done by both Sahil Sharma and me and it’s part of a project we are working on called 31skills: Must-Know Checklists & Resources For IT Professionals. This project aims to provide the must-know skills and the useful resources to different important jobs in the IT industry like DevOps, Site Reliability Engineers, IT Architects, Data Scientists ..etc
Please subscribe to 31skills and you will get an invitation to our community including (31skills learning path, DevOpsLinks & Shipped newsletters and an invitation to joins out Slack team chat) is just a buzzword and for recruiters, DevOps is a job.
I think DevOps is not just a buzzword but somehow it is a mix of all the above definitions: There is no digital transformation without the right methodologies, the right tools and the right engineers.
In a previous post I wrote The 15-point DevOps Check List that described an approach to implement DevOps in a business. This post is more about the skills required for a DevOps, Site Reliability Engineers and site engineers. Many of the points listed below are specific to *nix environments, this doesn’t mean that there is now DevOps environment for windows lovers.
This list is not exhaustive but enumerates only technical basic, must-know skills and some random thoughts. You may use them as a checklist to evaluate yourself or someone else or to prepare for your next DevOps/SRE job interviews.
This list is opinionated.
- First of all, be sure to understand the importance of the cultural points: read more here The 15-point DevOps Check List
- You should master *nix systems and have a good understanding of how Linux distributions work.
- Be at ease with Terminal. You may have GUIs to manage your servers but you have to LOVE the terminal no matter what’s the case, it is faster, secure and honestly it is easier once you master it.
- How to get the CPU/system info (cat /proc/version, /proc/cpuinfo, uptime, et. al.)
- How cron jobs works. Set cron jobs on specific days/time/month.
- How to know what OS you are running on your machine (cat /etc/lsb-release)
- Learn the difference between different *nix OSs and How to know what OS you are running on your machine (e.g. cat /etc/lsb-release)
- Difference between shells: sh/dash/bash/ash/zsh ..
- How to set and unset ENV variables. Exporting ENV variable is temporary, how to export permanent variables ?
- What are shell configuration files : ~/.bashrc, .bash_profile, .environment .. How to “source” settings for program initialization files.
- Knowing Vim, its configuration (.vimrc) and some of its basic tips is a must.
- How logging works in *nix systems, what are logging levels and how to work with log management tools (rsyslog, logstash, fluentd, logwatch, awslogs ..)
- How swapping works. What is swappiness. (swapon -s, /proc/sys/vm/swappiness, sysctl vm.swappiness ..)
- How to view/set network configuration on a system
- How to set static/dynamic IP address on a machine with different subnets? (Hint: CIDR)
- How to view/set/backup your router settings?
- How DNS works ? How to set-up a DNS server (Bind, Unbound, PowerDNS, Dnsmasq ..) ? What is the difference between recursive and authoritative DNS ? How to troubleshoot DNS (nslookup, dig ..etc)
- Get familiar with DNS and A, AAAA, C, CNAME, TXT records
- How SSH works, how to debug it and how you can generate ssh keys and do passwordless login to other machines
- How to set-up a web server (Apache, Nginx ..)
- What are the difference between Nginx and Apache ? When to use Nginx ? When to use Apache ? You may use both of them in the same web application, when and how ?
- How to set-up a reverse-proxy (Nginx ..)
- How to set-up a caching server ( Squid, Nginx ..)
- How to set-up a load balancer ( HAproxy, Nginx ..)
- What is an init system ? Do you know Systemd (used by Ubuntu since 15.04) , Upstart (developed by Ubuntu), SysV ..
- Get familiar with Systemd and how to analyze and manage services using commands like systemctl and journalctl
- Compiling any software from its source (gcc, make and other related stuff)
- How to compress/decompress a file in different formats via terminal (mostly: tar/tar.gz)
- How to set-up firewalls (iptables at least ufw) : set rules,list rules, route traffic, block a protocol/port ..
- Learn most used port numbers on which services runs by default (like: SSH (22), Web (80), HTTP/S (443) etc.)
- Learn how to live debug and trace running application in production servers.
- Be at ease with scripting languages. Bash is a must (Other scripting languages are very useful like Python, Perl..).
- Learn how to use at least one of the configuration management and remote execution tools (Ansible, Puppet, SaltStack, Chef ..etc). Your choice should be based on criterias like: syntax, performance, templating language, push vs pull model, performance, architecture, integration with other tools, scalability, availability ..etc.
- Learn how to configure and use continuous integration and continuous delivery tools like Jenkins, Travis CI, Buildbot, GoCd. Integrating this tools with other tools (like Selenium, build tools, configuration management software, Docker, Cloud providers’ SDKs ..etc) is helpful.
- Learn distributed version control system Git and its basic commands (pull/push/commit/clone/branch/merge/logs…etc.). Understand git workflows. Do you know how to revert a Git repository to a previous commit ?
- How to use SSH-keys. Try Github, Bitbucket or Gitlab .. to configure passwordless access to the repo/account
- Get familiar with tools like Vagrant to help you create distributable and portable development environments.
- Start looking into infrastructure as code and infrastructure provisioning automation tools like Terraform and Packer
- Start looking into containers and Docker. It’s underlying architecture (cgroups and namespaces). How it works?
- Start getting familiar with basic Docker commands (logs/inspect/top/ps/rm). Also look into docker hub (push/pull image)
- Start looking into container orchestration tools: Docker Swarm, Kubernetes, Mesosphere DC/OS, AWS ECS
- Dive into DB (MySQL or any other which you like)
- What is your backup strategy ? How do you test if a backup is reliable
- Do you know ext4, ntfs, fat ? Do you know Union filesystems ?
- Develop your Cloud Computing skills. Start by choosing a cloud infrastructure provider: Amazon Web Services, Google Cloud Platform, Digitalocean, Microsoft Azure. Or create your own private cloud using OpenStack.
- What about staging servers ? What is your testing strategy Unit Testing ? End-to-end ? So you really need staging servers ? Google “staging servers must die”.
- Read about PaaS/Iaas/Saas/CaaS/FaaS/DaaS and serverless architecture
- Learn how to use and configure Cloud resources from your CLI using Cloud Shells or from your programs using Cloud SDKs
- Are you familiar with the OSI Model and the TCP/IP model specifications ? What are the difference between TCP and UDP ? Do you know vxlan ?
- Master useful commands like process monitoring commands (ps, top, htop, atop ..), system performance commands (nmon, iostat, sar, vmstat ..) and network troubleshooting and analysis (nmap, tcpdump, ping, traceroute, airmon, airodump ..).
- Get to know HTTP status codes (2xx, 3xx, 4xx, 5xx)
- Are you familiar with IDEs (Sublime Text, Atom, Eclipse ..) ?
- Network packet analysis: tcpdump, Wireshark ..
- What happens exactly when you hit google.com in the browser? From your browser’s cache, local DNS cache, local network configuration(hosts file), routing, DNS, network, web protocols, caching systems to web servers (Most basic question yet difficult if goes deep).
- Get familiar with the mumble-jumble of Kernel versions and how to patch them.
- Get familiar with how SSL/TLS works and how digital certificates works (https)
- Get familiar with secure protocols: TLS, STARTTLS, SSL, HTTPS, SCP, SSH, SFTP, FTPS ..
- Know the difference between PPTP, OpenVPN, L2TP/IPSec
- How to generate checksums (md5, SHA ..) to validate the integrity of any file
- Get to know the difference between Monolithic and Microservices architecture.
- Get to know the pro/cons of Microservices architecture and start building similar architectures
- Do you know what is ChatOps ? Have you tried working with one of the known frameworks ? Hubot, Lita, Cog ?
- How do you make zero downtime deployment ? What is your strategy to make rollbacks, self-healing, auto-scalability ?
- Get familiar with APIs and services: RESTfull, RESTful-like, API gateways, Lambda functions, serverless computing,SOA, SOAP, JMS, CRUD ..
- Read about stateless and stateful applications
- Read about DevOps glossary (Google it)
- How to secure your infrastructure, network and running applications ?
- Learn how set-up, configure and use some monitoring systems (Nagios, Zabix, Sensu, prometheus..etc)
- Read about Open Source and how you can contribute to Open source projects. For more info:
- You should be able to do post-mortem if something bad happens to your systems. Make a detailed documentation about what went wrong and how we can prevent not to let it happen in future again.
- Try to learn the approach how experts from StackOverflow are solving any problem. Always remember, it’s the technology which keeps on changing not the basics. Basics always remains the same.
- Make Google, StackOverflow, Quora and other professional forums your friends.
- Try to establish good development practices and a solid architecture.
- Learn how to scale at production level.
- Follow open-source projects (Kubernetes/Docker etc.) or what excites you.
- Ask questions/doubts/issues on mailing-lists/public forums/tech meetups and learn from those.
- Follow like-minded folks from the community and be updated with latest tech trends.
- Follow some decent tech companies engineering blogs (We follow: Google/Uber/Quora/Github/Netflix). This is the place from where you can learn straight from the experts and get a chance to see their approach to solve any problem.
- Browse a few aggregators like Reddit, hackernews, medium .. etc.
- Follow like-minded developers and tech companies on twitter. ( I am always reading articles and watching talks/conferences, post-mortems are some of my favorite content. I also follow a few github repos to see what’s going on with the technology that I use.)
- Read various technology related blogs and subscribe to DevOps Newsletters.
- If possible attend local area meetups and conferences. You will get a chance to learn a lot from seniors and others.
- Learn about scalability and highly distributed systems. How to keep them UP and Running all the time?
- Last but not the least… Read Books.
If you have the majority of these skills, you can be sure you have the prerequisites to DevOps, SRE and system engineering.
You can’t learn all these in one-shot. But having a mind-set is the main thing. It will surely take time even to get familiar with all these but as they say journey has the fun. You will fail many times, learn from your mistakes and don’t repeat them.
Always remember, we all are learners here. We learn by hit and trial. Don’t feel shy in failing because that’s how we learn.
We will be happy to hear your suggestions to add other points to this list.
31Skills.com
31Skills is coming soon, we are working on it and it will be released soon, if you are interested in joining us, subscribe here and you will be invited once it’s online.
Sahil is a Site Reliability Engineer at Formcept where he work in a DevOps team to make Big Data Analysis accessible to enterprises and help them get actionable and fast insights from their data. You can follow him on Twitter
Connect Deeper
If you resonated with this article, please subscribe also to 31skills : An Online Community Of +1000 Diverse & Passionate DevOps, SysAdmins & Developers From All Over The World.
If you’re interested in learning technologies like AWS, GCP, Docker ..etc
Don’t forget to pre-register and get your discount coupon to our next courses session, leave your contact information here and we will be in touch with you soon.
You can find me on Twitter, Clarity or my blog and you can also check my books: SaltStack For DevOps,The Jumpstart Up & Painless Docker.
This work was done in collaboration with Sahil Sharma, a Site Reliability Engineer at Formcept where he work in a DevOps team to make Big Data Analysis accessible to enterprises and help them get actionable and fast insights from their data. You can find Sahil on Twitter.
If you liked this post, please recommend and share it to your followers.<< | https://hackernoon.com/the-must-know-checklist-for-devops-system-reliability-engineers-f74c1cbf259d?gi=b72c48eb4fbb | CC-MAIN-2018-13 | refinedweb | 2,057 | 66.03 |
Apache OpenOffice (AOO) Bugzilla – Issue 90553
import MathML : Pb with ^
Last modified: 2014-12-27 16:48:36 UTC
This equation isn't imported correctly in OO because of the char ^:
<math xmlns="">
<mstyle fontfamily="serif">
<mrow>
<msub>
<mover>
<mi>t</mi>
<mo accent="true">^</mo>
</mover>
<mi>A</mi>
</msub>
</mrow>
</mstyle>
</math>
Created attachment 54359 [details]
Sample MML that show the PB
Created attachment 54360 [details]
bad view in openOffice
Created attachment 54361 [details]
Good View in Firefox
MRU->TL: the import of the attached MML gives "font serif t csup widehat_A",
but it should be more sth. like "font serif {hat t}_A". The csup is not
necessary because of widehat; also the widehatis in wrong position.
Note that this bug can be triggered by opening a ODT file that comes from
Microsoft Word.
This has also been reported in the redhat bugzilla
I created and put up a patch for this bug for libreoffice. I would guess that it can be used for Open Office as well:
@jrincayc: Your patch is appreciated. Please attach it here and assure, that you give the patch under Apache License, Version 2.0 ().
Created attachment 78525 [details]
Patch to fix all simple accent problems from Libre Office
Patch created for Libre Office, but I think it should probably work with Open Office, and I am giving the patch under Apache License, Version 2.0.
I have tried LO3.6 and it does not show the formula as I can see it in the browser. Isn't this patch applied to LO3.6?
I have applied the patch to my local working copy of AOO. There too I still see the wrong formula.
Has someone verified, that the patch works as intended?
What I did:
Open a new formula document.
Tools > Import Formula...
Choose the file attached to this bug.
Created attachment 78883 [details]
simple accents
The patch does not solve the bad rendering of the first attachment, but is solves wrong import for those simple accents, which can be applied from the 'Attributes' category in Math. The attached file contains a collection of that characters.
"regina" committed SVN revision 1370843 into trunk:
#i90553# fix simple accents in MathML importPatch by: Joshua Cogliati;Review ...
adjusted target to version that will contain the fix
Single accents are good, but the initial document is still not rendered correctly. There seems to be an additional problem here. | https://bz.apache.org/ooo/show_bug.cgi?id=90553 | CC-MAIN-2017-04 | refinedweb | 403 | 62.27 |
Canon Powershot A450
Here you can find all about Canon Powershot A450 like manual and other informations. For example: instructions, memory card, software download, drivers, user guide, review, price, battery, digital camera.
Canon Powershot A450 manual (user guide) is ready to download for free.
On the bottom of page users can write a review. If you own a Canon Powershot A450 please write about it to help other people. [ Report abuse or wrong photo | Share your Canon Powershot A450 photo ]
Manual
Canon Powershot A450
Video review
Canon PowerShot A490
User reviews and opinions
Comments posted on are solely the views and opinions of the people posting them and do not necessarily reflect the views or opinions of us.
Documents
The Components Guide Preparations Shooting
Photo of PowerShot A460
Playback/Erasing Menus and Settings Printing
Downloading Images to a Computer
Basic Camera User Guide
Please Read This First
This guide explains how to prepare the camera and use its basic features.
CDI-E268-010
2007 CANON INC.
PRINTED IN CHINA
Flowchart and Reference Guides
The following guides are available. Refer to them as necessary according to the flowchart below.
For information on included items and items sold separately System Map
The Components Guide Preparations Installing the batteries ZoomBrowser EX/ ImageBrowser Software User Guide PDF manuals available on the Canon website. Imaging/informatione.html
You may not be able to achieve the full performance of this camera with the included memory card.
In this guide, the Basic Camera User Guide is called the Basic Guide, and the Advanced Camera User Guide is called the Advanced Guide.
The Components Guide
Front View
def b a c g h i
Attaching the Wrist Strap
a Wrist Strap Mount b Speaker c Flash (p. 13) d AF-assist Beam (Advanced Guide p. 20) e Red-Eye Reduction Lamp (p. 14) f Self-Timer Lamp (p. 16) g Microphone (Advanced Guide p. 54) h Viewfinder Window (Advanced Guide p. 17) i A/V OUT (Audio/Video output) Terminal (Advanced Guide p. 62) j Lens In order to avoid dropping the camera, wear the wrist strap when using the camera.
Back View
e f g h i
aLCD Monitor (Advanced Guide p. 12) bViewfinder (Advanced Guide p. 17) cDIGITAL Terminal (p. 27) dDC IN (power input) Terminal (Advanced Guide p. 89) eTerminal Cover fMemory Card Slot / Battery Cover Lock (p. 5) gMemory Card Slot / Battery Cover (p. 5) hDate Battery Cover (Advanced Guide p. 92) iTripod Socket The LCD monitor may be covered with a thin plastic film for protection against scratches during shipment. If so, remove the film before using the camera.
Controls
a b c d
i j k l
a Indicators (p. 4) b Mode Dial (pp. 8, 18) c Shutter Button (p. 8) d Power Button (p. 8) e DISP. (Display) Button (Advanced Guide p. 12) f MENU Button (p. 21, Advanced Guide p. 19) g FUNC./SET (Function/Set) Button (p. 20, Advanced Guide p. 18) h (Print/Share) Button (pp. 22, 30) i (Macro)/ (Infinity)/ Button (p. 15) j (Telephoto while shooting) / (Magnify in playback mode)/ Button (p. 12, Advanced Guide p. 50) Button (p. 13) k (Flash)/ l (Wide Angle while shooting) / (Single Image Erase) / Button (p. 12, p. 19, Advanced Guide p. 28): Ready to shoot (flash on) Blinking Orange:Ready to shoot (camera shake warning), charging flash Lower Indicator Yellow: Macro mode/Infinity mode Blinking Yellow: Focusing difficulty (camera beeps once)
Preparations
1. Installing the batteries.
1. Slide the memory card slot/battery cover lock (a) and press down while opening the cover (b). 2. Insert the batteries. a
Positive end (+) Negative end ()
See the Advanced Guide: Battery Handling (p. 83).
2. Inserting the Memory Card.. 85). See the Advanced Guide: Formatting Memory Cards (p. 25).). 3. Confirm that the correct time is displayed and press the FUNC./SET button (c). The date and time can also be set in the Set up menu (p. 21). The date/time setting screen will appear when the camera power is turned on for the first time, or when the capacity of the lithium date battery is depleted.
See the Advanced Guide: Replacing the Date Battery (p. 92).
Setting the Display Language
1. Turn the mode dial to (playback) (p. 18). 2. Hold down the FUNC./SET button and press the MENU button. 3. Use the , , or button to select a language and press the FUNC./SET button. The display language can also be set in the Set up menu (p. 21).
Shooting
1. Press the power button.
Power Button
The start-up sound will play and the start-up image will display in the LCD monitor. Pressing the power button again turns the power off. Pressing the power button while pressing and holding the DISP. button will turn on the mute setting which will DISP. Button mute all sounds except for warning sounds.
See the Advanced Guide: Using the LCD Monitor (p. 12). See the Advanced Guide: Power Saving Function (p. 17). See the Advanced Guide: Set up Menu (p. 21).
2. Turn the mode dial to
(Auto).
3. Aim the camera at the subject. 4. Focus and shoot.
1. Press the shutter button halfway to focus. When the camera focuses, the camera beeps twice and the indicator lights green (orange when using the flash). Also, the AF frame appears in green on the LCD monitor at the point where the camera is focused.
2. Press the shutter button fully to shoot. The shutter sound will play and the image will record. The indicator will blink green while the image is recorded to the memory card.
See Indicators (p.. 20). See Erasing (p. 19).
Selecting a Shooting Mode
1. Turn the mode dial to the desired mode (a).
, or modes
or button (c). 1.Press the FUNC./SET button (b). 2.Select a shooting mode using the 3.Press the FUNC./SET button (d).
Shooting Modes
The camera automatically selects settings.
Auto Manual
Allows you to select settings yourself, such as the exposure compensation, white balance, My Colors or ISO speed.
Manual
Super Macro
Allows you to approach closer than in Macro mode to take larger close-ups. At maximum wide angle, the distance from the end of the lens to the subject can range from cm (0.3 2.0 in.). See the Advanced Guide (p. 28)
Portrait
Produces a soft effect when photographing people.
Night Snapshot
Allows you to take snapshots of people against twilight or night backgrounds by reducing the effects of camera shake even without using a tripod.
Kids&Pets
Allows you to capture subjects that move around, such as children and pets, without missing photo opportunities.
Indoor
Prevents camera shake and maintains the subject's true color when shooting under fluorescent or tungsten lighting.
Special Scene.
Shoots a movie when you press the shutter button. You can set it to the (Standard) or (Compact) mode, which is convenient for email attachments.
See the Advanced Guide (p. 32).
The shutter speed is slow in mode. Always use a tripod to avoid camera shake. In , or mode, the ISO speed may increase and cause noise in the image depending on the scene being shot. In mode, shoot with the subject more than 1 m (3.3 ft.) away from the front of the lens.
Using the Zoom
1. Press the
button.
You can adjust the zoom for the following focal lengths in 35mm film equivalent terms. PowerShot A460: mm PowerShot A450: mm
Telephoto: Zooms in on the subject. Wide Angle: Zooms out from the subject.
Using the Flash
button to cycle through flash settings.
(Auto) (On) (Off)
See Setting the Red-Eye Reduction Function (p. 14). See Setting the Slow Synchro Function (p. 14).
option cannot be set in
(Auto) mode.
See the Advanced Guide: Functions Available in Each Shooting Mode (p. 112). See Selecting a Shooting Mode (p. 10).
You are recommended to shoot with the camera attached to a tripod or other device if the camera shake warning icon ( ) appears. When the LCD monitor is on and flash recharging begins, the indicator blinks orange and the LCD monitor turns off. When recharging ends, the indicator turns off and the LCD monitor turns on. The time required for flash recharging will change depending on usage conditions and remaining battery power.
Setting the Red-Eye Reduction Function
You can set whether the camera automatically fires the red-eye reduction* lamp when the flash fires.
* This function reduces the red appearance of eyes when they reflect light back from the flash.
(Rec.) Menu
(Red-Eye)
[On]*/[Off].
See Menus and Settings (p. 21).
* (Slow Synchro)
[On]/[Off]*.
Slow Synchro cannot be set in
When [Slow Synchro] is set to [On], camera shake may become a factor. Use of a tripod is recommended.
Shooting Close-ups (Macro)/Infinity Shots
button to turn off the
To cancel the macro mode, press the or display.
See the Advanced Guide: Shooting Magnified Close-Ups (Super Macro) (p. 28)
Use this mode to shoot close-ups of flowers or small items. Image Area at Minimum Focusing Distance from End of Lens to Subject Maximum wide angle setting: 53 x 40 mm (2.0 x 1.5 in.) Minimum focusing distance: 5 cm (2.0 in.) (PowerShot A460) Maximum telephoto setting: 66 x 50 mm (2.6 x 2.0 in.) Minimum focusing distance: 25 cm (9.8 in.) (PowerShot A450) Maximum telephoto setting: 77 x 58 mm (3.0 x 2.3 in.) Minimum focusing distance: 25 cm (9.8 in.) Use this mode when the distance from the end of the lens to the subject is 3 m (9.8 ft.) or greater. Shooting
Infinity
Use the LCD monitor to compose close-ups in macro mode since images composed with the viewfinder may be off-center. Confirm that you are within range when using the builtin flash (Advanced Guide p. 96). The mode cannot be set in (Auto) mode.
Using the Self-Timer
1. FUNC. Menu
* (Drive Mode)
See Menus and Settings (p. 20).
When the shutter button is pressed fully, the self-timer lamp will blink. When using red-eye reduction, the self-timer lamp will blink and then stay lit for the last 2 seconds. To cancel the self-timer, follow step 1 and select.
10 sec. Self-Timer: Shoots 10 sec. after you press the shutter button. 2 sec. before the shutter releases, the self-timer sound and lamp will speed up. 2 sec. Self-Timer: Shoots 2 sec. after you press the shutter button. The self-timer sound beeps quickly when you press the shutter button and the shutter releases 2 sec. later. Custom Timer: You can change the delay time (010*1, 15, 20, 30 sec.) and number of shots (110*2) (p. 17). When [Delay] is set to 2 or more sec., the self-timer sound begins to beep 2 sec. before the shutter releases. When [Shots] is set higher than 1, the self-timer sound only beeps before the first shot. *1 Default setting. *2 Default setting is 3 shots.
This setting cannot be set in some shooting modes.
Changing the Delay Time and Number of Shots ( )
1. FUNC. Menu (Drive Mode) (Custom Timer).
2. Press the MENU button. 3. Select [Delay] or [Shots] using the change the settings using the or the FUNC./SET button.
or button and button, then press. Turn the mode dial to
(playback) (a).
The last recorded image will display. a If you have played back images between shooting sessions however, the last image viewed will display (Resume Playback) instead of the last recorded image. If the memory card has been switched, or the b images on the memory card have been edited with a computer, the newest image on the memory card appears.
2. Use the
or to view (b).
button to display the image you wish
Use the button to move to the previous image and the button to move to the next image. Holding the button down advances the images more rapidly, but shows them less clearly.
See the Advanced Guide for the various playback methods available.
Erasing
1. In the playback mode, use the
or button to select an image to button erase (a) and press the (b).
2. Confirm that [Erase] is selected
and press the FUNC./SET button (c).
To exit instead of erasing, select [Cancel].
Please note that erased images cannot be recovered. Exercise adequate caution before erasing an image.
See the Advanced Guide: Erasing All Images (p. 63).
Playback/Erasing
Menus and Settings
Settings for the shooting, playback or print modes or such camera settings as the date/time and sounds are set using the FUNC., Rec., Play, Print or Set up menu.
FUNC. Menu
This menu sets many of the common shooting functions. a b e
This example shows the FUNC. menu in
aTurn the mode dial to , , or. bPress the FUNC./SET button. cUse the or button to select a menu item. Some items may not be selectable in some shooting modes. dUse the or button to select an option for the menu item. You can select further options with the MENU button for some options. After selecting an option, you can press the shutter button to shoot immediately. After shooting, this menu will appear again, allowing you to adjust the settings easily. ePress the FUNC./SET button.
See the Advanced Guide: Menu List (p. 20).
Rec., Play, Print and Set up Menus
Convenient settings for shooting, playback or printing can be set with these menus. (Rec.) Menu (Set up) Menu e
b You can switch
between menus with the or button when this part is selected.
This example shows the Rec. menu when in mode. In playback mode, the Play, Print and Set up menus display.
a Press the MENU button. b Use the or button to switch between menus. You can also use the zoom lever to switch between menus. c Use the or button to select a menu item..
Connect the camera to a direct print compatible printer*1 with a cable and simply press the button on the camera.
1. Connect the camera to a direct print compatible printer
and turn on the printers power.
Canon Brand Printers
Compact Photo Printers *2 (SELPHY Series)
Camera
Interface Cable.
2. Turn on the power in playback mode and confirm that
, or is displayed in the upper left of the LCD monitor (a).
The button will light blue. The displayed icon will vary according to the printer model. will display for movies.
3. Select an image to print using the
and press the
button (b)
button (c).
button will blink blue and printing will start.
See the Advanced Guide: Setting the DPOF Print Settings (p. 64). See the Direct Print User Guide. See the user guide for your printer.
The following methods can be used to download images recorded by the camera to a computer. Some methods, depending on the OS used, may not be available. Please read System Requirements (p. 25) in advance.
Camera to Computer Connection
Supplied Software Downloading Method OS Windows 2000 Windows XP Windows Vista Mac OS X Install It Computer Procedure Camera Procedure Do Not Install It Computer Procedure
Computer System Requirements Connecting the Camera to a Computer Downloading Images to a Computer
Basic Guide (p. 25) Software Starter Guide Basic Guide (p. 27) Software Starter Guide
Basic Guide (p. 27)
Basic Guide (pp. 28, 29) Windows Vista Windows 2000/Windows XP Windows Vista USB Canon Utilities - ZoomBrowser EX - PhotoStitch Canon Camera TWAIN Driver 200 MB or more 40 MB or more 25 MB or more Pentium 500 MHz or higher Pentium 1.3 GHz or higher 256 MB or more 512 MB or more Downloading Images to a Computer
Computer Model CPU RAM Interface Free Hard Disk Space
Display
1,024 x 768 pixels/High Color (16 bit) or better
Macintosh
OS Computer Model CPU RAM Interface Free Hard Disk Space Display Mac OS X (v10.3 v messages to proceed.
3. When the installation is complete, click either the [Restart] or [Finish] button that appears. 4. Remove the CD-ROM from the drive when your normal desktop screen appears.
The window to the right will appear when you double-click the icon in the CDROM. Select [Install] and follow the onscreen messages to proceed.
2. Connecting the camera to a computer.
1. Use the supplied interface cable to connect the computers USB port to the cameras DIGITAL terminal. Slip your fingernail under the edge of the cameras terminal cover, lift it open and plug the interface cable in all the way.
USB Port DIGITAL Terminal
2. Turn the cameras mode dial to (playback) and turn on the power. The camera and computer will be able to communicate.
Always grasp the sides of the connector when disconnecting the interface cable from the cameras. 26).
All Images New Images Transfers and saves all images to the computer. Transfers and saves to the computer only the images that have not been previously transferred.
Transfers and saves to the computer only the DPOF Trans. Images images with DPOF Transfer settings (Advanced Guide p. 67). Select & Transfer.
All Images/New Images/DPOF Trans. Images
2. Select
, or button.
The images will download. The button will blink blue while downloading is in progress. The display will return to the Direct Transfer menu when the download is complete. To cancel the download, press the FUNC./SET button.
Select & Transfer/Wallpaper
or , and press the FUNC./SET button). (or the FUNC./SET button).
The images will download. The button will blink blue while downloading is in progress. Images can also be selected during index playback (Advanced Guide p. 51). Press the MENU button to return to the Direct Transfer menu.
button (or the button
3. Select images to download and press the.
Platinum Indulgence
Every time you use your Standard Chartered Platinum Elite Card, we find unique ways to thank you with rewards that spells Indulgence all the way, carefully chosen to compliment your exclusive lifestyle. As a Platinum Elite Cardmember you can unwind in the lap of luxury at Cliveden Castle, made famous by guests such as Sir Winston Churchill, Charlie Chaplin, King George I and President Roosevelt, or choose from a range of premium offerings handpicked for discerning people like you.
Platinum Indulgence Rewards
Rewards Category Platinum Indulgence Electronics Rewards Holiday at Cliveden house, London Nikon Binocular - Sports Star EX (10x25 water proof) Canon Powershot A450 Camera with 1GB card +charger Celestron PowerSeeker Telescope 127EQ Bose Quietcomfort 2 Acoustic Head phones HTC T3232 Touch 3G Mobile Canon Handycam - DC 230 Jamo A102HCS5 speakers Sony PSGB Canon EOS 400D camera with 1GB card Philips - 42LCD television Bose Lifestyle 38 Series home entertainment system Cross Pen - Century II Series Ray Ban Aviator Series Mont Blanc fine leather steel buckle belt Mont Blanc Platinum plated cuff links Tissot T Touch watch with steel Omega Speed Master watch Tag Heuer Carrera CV 2011 watch Osim u-Papa Drum Massager La-Z-Boy Broadway single seater recliner Osim Comfort Chair - Noro Melody NR85 Palador 5 DVD world cinema box set Hourglass accessories Palador 10 DVD world cinema box set OSIM u-Sonic jewellery cleaner La Opala dinner set - hand painted Artdinox - Bar accessories 8 GB ipod Artdinox Square dinner set 30 GB ipod Flying Returns - Indian Airlines 1.2 Reward Points = 1 AOMPS JP Miles - Jet Airways 1.2 Reward Plus point = 1 Jet Privilege Miles King Miles - Kingfisher Airlines 1.2 Reward Points = 1 King Mile Points Code 5,00,000 14,910 16,810 32,940 35,270 39,560 46,740 59,520 60,310 93,600 1,75,110 3,63,200 3,140 7,850 26,860 32,480 64,280 2,46,390 2,96,530 31,020 94,340 2,23,200 3,540 5,210 6,680 9,630 14,380 17,540 18,900 28,170 30,910 L102 JA1P KF1P 031
Accessories
Relaxation & Wellness Entertainment & Home Accessories
Air Miles
Holiday* at Cliveden House, London
Be the king of the castle
Points: 5,00,000 (Code: 000) A grand Italianate mansion with a palpable sense of history Called home by some of the most famous names in English and American history, including three Dukes, the Prince of Wales and guests have included every British monarch since George I, as well as Charlie Chaplin, Winston Churchill, Harold Macmillan, President Roosevelt, George Bernard Shaw, John Profumo and Christine Keeler Private butler Cruise the river Thames from Spring Cottage in one of Clivedens famous vintage launches
*To avail the holiday at Cliveden House Cardmember will have to intimate Standard Chartered Bank atleast 3 months in advance and is subject to availability.
Electronics
Nikon Binocular Sports Star EX
See farther than the rest
Points: 14,910 (Code: 001) Waterproof, fog-proof, and shockproof performance All metal chassis in lightweight polycarbonate shell Rubber-coated body for firm, non-slip grip Magnification: 10x Objective lens: 25mm
Canon Powershot A450
When youre not in the mood for a thousand words
Points: 16,810 (Code: 002) 5.0 Megapixel 3.2x Optical zoom Image sensor Optical viewfinder DIGIC II Imaging processor
Celestron 127 EQ PowerSeeker Telescope
Reach for the stars
Points: 32,940 (Code: 003) The ideal combination of quality, value, features and power Coated glass optical components for enhanced image, brightness and clarity Equatorial mount design Aluminum tripod Accessory tray 5x24 Finderscope Eyepieces: 20mm-1.25 and 4mm-1.25 3x-1.25 Barlow Lens
Bose QuietComfort 2 Acoustic Noise Cancelling Headphones
Quietly setting a whole new standard
Points: 35,270 (Code: 004) Patented Acoustic Noise Cancelling headphone technology Acoustic Structure of the TriPort headphone system Active equalization Detachable audio cable with built-in Hi/Lo switch QuietComfort ear cushions Adjustable headband Dual plug and 1/4-inch stereo phone adapter 5-feet extension cord Portable carry case
HTC T3232 Touch 3G
Cutting-edge people deserve cutting-edge technology
Points: 39,560 (Code: 005) GSM900/1800/1900 certified Touchpad or dialing pad option Inbuilt answering machine 192MB of flash ROM and 64MB of RAM, alongside a side-mounted miniSD card slot Intel XScale processor at 416Mhz Wireless connectivity of 802.11g (and thus 802.11b by default) as well as Bluetooth Runs on Windows Mobile 5.0, with capabilities for push e-mail, office document viewing, web browsing and of course, playing Bubble Breaker
Canon Handycam DC 230
Store your most remarkable moments for posterity
Points: 46,740 (Code: 006) Dimensions (WxHxD) 2.1 x 3.5 x 5 in. (154 x 90 x 128mm) Audio Recording system Dolby Digital 2ch (AC-ch) Image Sensor 1/6-inch CCD, 1.07 Megapixels Lens f = 2.6 - 91 mm, f/2.0 - 5.0, 35x Power Zoom Viewfinder 27 - inch TFT Colour LCD Screen 2.7 - inch TFT Colour Recording Media DVD-R/-RW/-R DL
Jamo A102HCS5
Match wavelength with the best
Points: 59,520 (Code: 007) The system consists of two A102 satellite front speakers, two A102 satellite surround speakers, a A10 CEN center speaker and a powered SUB 200 subwoofer Magnetic shielding Auto On/Off
Sony PSGB
Make some time for play
Points: 60,310 (Code: 008) Media type: BD-ROM, CD-ROM, DVD-ROM Cell Broadband Engine 256 MB integrated memory NVIDIA RSX output Video adapter memory of 256 MB installed Bluetooth, IEEE 802.11 connectivity Includes Spiderman 3 Blu-ray disc movie
Canon EOS 400D with 1GB card
Bring out the professional in you
Points: 93,600 (Code: 009) First DSLR camera equipped with the new EOS Integrated Cleaning System - Canons comprehensive measures to minimise the effects of dust on images 10.1 Megapixel CMOS sensor and powerful DIGIC II Image processor Canon EF lens mount, compatible with over 60 Canon EF and EF-S interchangeable lenses for endless photographic possibilities Includes an extensive range of accessories such as the acclaimed E-TTL II flash metering system to match users growing needs
Philips - 42 LCD TV
Experience life bigger than it is
Points: 1,75,110 (Code: 010) Uses Pixel Plus technology to produce breathtaking natural pictures Incredible Surround Sound dramatically magnifies the sound field Integrated digital tuner, with a wide selection of free-view channels without the need of an additional receiver
Bose Lifestyle 38 DVD Entertainment System
Introducing the new Lifestyle 38 DVD home entertainment system from Bose
Points: 3,63,200 (Code: 011) Direct/Reflecting cube speaker arrays Acoustimass module Horizontal center-channel speaker Lifestyle media center VS-2 video enhancer ADAPTiQ audio calibration system evaluates your rooms acoustics and where your speakers are placed uMusic Intelligent Playback system to digitally store up to 200 hours of your music 1080p over HDMI
Cross Century II Lustrous Chrome Ballpoint Pen
Let your writing speak for you
Points: 3,140 (Code: 012) Ball-Point pen with Selectip rolling ball Available in Silver Blue lacquer
Ray Ban Aviator Series Large Metal II
For people with impeccable style
Points: 7,850 (Code: 013) Polarized lens for better protection against the sun Metal rims that will never go out of fashion
Mont Blanc Classic Line Belt
Make a lasting subtle impression
Points: 26,860 (Code: 014) Full grained calf leather 3 x 120 cm strap Polished Palladium-plated round shaped box buckle with a Mont Blanc signet Reversible
Mont Blanc Elegance Cuff Links
Understated Elegance
Points: 32,480 (Code: 015) Platinum-plated round cuff links Black onyx inlay
Tissot T Touch with Steel
Explore without getting lost
Points: 64,280 (Code: 016) Unisex, watch-cum-thermometer-cum-barometercum-altimeter-cum-compass-cum-chronographcum-alarm Water resistance of up to 30m Glass-tactilis sapphire crystal Hour indicators-index Bracelet-stainless steel grey Movement caliber - e 40.305 quartz
Omega Speed Master
Style at the flick of the wrist
Points: 2,46,390 (Code: 017) Scratch resistant sapphire in a case of stainless steel Fold-over-with-push-button clasp Includes tachometer Water resistance of 330 feet
Tag Heuer Carrera CV 2011
To keep up with your fast-paced life
Points: 2,96,530 (Code: 018) Stainless steel design Chronograph, date indicator, luminous, stopwatch, tachymeter, water resistant, scratch resistance
Relaxation & Wellness
OSIM u-Papa
Power Drum Massager
Points: 31,020 (Code: 019) Intense taiko strength drum-massage penetrates deep into your muscle layers easing away all aches and strains Symmetrical 6 point stimulation for deep tissue relief in the back, hips, thighs, calves and feet Customise the massage to your need
La-Z-Boy Recliner
For those deserving the best in comfort
Points: 94,340 (Code: 020) Rolled arm design Smooth back design with chaise seat
OSIM Noro Melody
Total relaxation for your body, mind and soul
Points: 2,23,200 (Code: 021) Music and Massage - The perfect combination 4 manual massage programme for complete indulgence Instant relief for your calves and feet
Entertainment & Home Accessories
Akira Kurosawa Collectors Box Set
Because any cinema collection is incomplete without Kurosawa
Points: 3,540 (Code: 022) The 5 films: Seven Samurai, Throne Of Blood, Red Beard, High And Low, Yojimbo 5 masterpieces from Oscar winning director A must have, first time ever collection in India packaged in an elegant box set Films have won 60 awards and 18 nominations worldwide
Hourglass Accessories at Work and Home
Reflection of your personality and taste
Points: 5,210 (Code: 024) Form and function merge with strength and durability in steel and varied raw materials to create the perfect combination of innovative style and design Art in steel at home
World Cinema Collectors Box Set
The Greatest, The Classiest Simply The Best Cinema
Points: 6,680 (Code: 025) The 10 films: Bed and Board, Shoot The Piano Player, Dead Man, Down By Law, Wild Strawberries, Summer Interlude, End Of Violence, Infernal Affairs, Infernal Affairs 2, Infernal Affairs 3 The Directors: Francois Truffaut, Ingmar Bergman, Jim Jarmusch, Wim Wenders, Wai Keung Lau & Sui Fai Mak
OSIM u-Sonic
Add more sparkle to your accessories
Points: 9,630 (Code: 026) Cleans jewellery, glasses, watches and other small items without cleaning solutions or scrubbing Employs the use of ultrasonic wave energy technology and water Environmentally friendly, sleek, compact and energy efficient with an automatic timer
La Opala Dinner Set
Add elegance to every meal
Points: 14,380 (Code: 027) Hand-painted dinner sets comprising 23 pieces: 6 full plates, 6 quarter plates, 6 soup bowls, 2 medium serving bowls with lids, 1 round rice plate Convenient for everyday use as it is made of microwave-safe, chip-resistant and 100% recyclable material
Artdinox Bar Accessories
Art that can be appreciated by a select few
Points: 17,540 (Code: 028) Stainless steel in matte finish Redefine staid accessories with a touch of newage design
8 GB iPod
Get your music to dance to your tune
Points: 18,900 (Code: 029) Larger, brighter display with the most pixels per inch of any Apple display iPod Nano stirs up visual effects from the outside in-up to 5 hours of video or up to 24 hours of audio on a single charge Anodized aluminum top and polished stainless steel back
Artdinox Dinner Set
Serve food with panache as an accompaniment
Points: 28,170 (Code: 030) Light-weight stainless steel serving dishes, bowls and trays, as well as cutlery in a sleek matte finish Trendy, elegant designs in combinations of steel and ceramic, and steel and glass
30 GB iPod
Food for your soul
Points: 30,910 (Code: 031) Stores up to 7,500 songs, 20,000 photos, or 75 hours of video playback 2.5-inch (diagonal) colour LCD with LED backlight Up to 14 hours of music playback, up to 3 hours of slideshows with music, up to 2 hours of video playback Comes with ear-bud headphones and USB cable Compatible with Mac OS X v10.3.9 or later, Windows 2000 with Service Pack 4 or later, or Windows XP Home or Professional with Service Pack 2 or later
Flying Returns - Indian Airlines
Gift code: L102 Convert your Rewards Plus points to Add-on Mileage Points (AOMPS). Add these AOMPS to your tally of FR mileage points & redeem them for Free tickets 1.2 Reward Plus point = 1 AOMPS
JP Miles - Jet Airways
Gift code: JA1P Convert your Rewards Plus points to JP Miles Redeem these JP Miles for free flights on Jet Airways / Jet Airways Konnect / Jet Lite and 21 airline partners of JetPrivilege, the frequent flyer programme of Jet Airways. 1.2 Reward Plus point = 1 Jet Privilege Miles
King Miles - Kingfisher Airlines
Gift code: KF1P Convert your Rewards Plus points to King Miles Add these miles to your tally of King Miles mileage points & redeem them for Free Tickets. 1.2 Reward Plus point = 1 King Mile
The Platinum Indulgence Rewards- Programme Details
The Standard Chartered Platinum Indulgence Rewards programme is open only to Standard Chartered Platinum Elite Cardmembers. This rewards programme will not be available to other Credit Cards of Standard Chartered Bank unless otherwise communicated in writing by Standard Chartered Bank The scheme will remain open till such time as may be terminated by Standard Chartered Bank at its sole discretion Offers against all products and services featured in the catalogue are valid for limited period and Standard Chartered Bank reserves the sole right to exclude these in subsequent editions of the catalogue if any No accumulation or carry over or redemption of reward points will be permissible, if on the relevant date any Card in the Card account be it a Primary, Supplementary, Multiple or any other Card has been withdrawn or closed or cancelled or reinstated or is liable to be cancelled / withdrawn or if the Standard Chartered Card account is a delinquent account or if there is any breach of the terms and conditions of the Cardmembers agreement. The reward points will lapse in the event that such a Card account is closed either voluntarily by the Cardmember or by Standard Chartered Bank at its discretion whether or not the Cardmember dues are cleared. Should the Card account be reinstated, either by the Cardmember or by Standard Chartered Bank, the Cardmember will not get the benefit of any points accrued prior to cancellation or withdrawal or closure of the Card account In the event of voluntary closure of the Standard Chartered Platinum Elite Card by a Cardmember, the Reward points that are in the Card Account can be redeemed within a month of such closure. Failure to redeem these points within a month of closure will lead to the Reward points automatically lapsing Redemption Points accrued can only be redeemed by the Primary Cardmember and not by a Supplementary Cardmember Cardmembers need to have a minimum of 500 Reward points whenever or 1st time they wish to redeem their Platinum Reward points The Platinum Reward points are redeemable only against products, vouchers or services featured in the Platinum Rewards catalogue and against any other products, vouchers or services as intimated from time to time by Standard Chartered Bank under the Platinum Indulgence Rewards programme All products featured in the Platinum Indulgence Rewards catalogue are subject to availability of the goods and supplier warranty restrictions at the time of redemption. Standard Chartered Bank gives no warranty (whether expressly or implied) whatsoever with respect to product / services acquired under the Platinum Indulgence Rewards programme either directly through the Platinum Rewards programme or through other partner loyalty programmes. In particular, Standard Chartered Bank gives no warranty with respect to the quality of goods acquired or their suitability for any purpose The gift article would be addressed to the customers name and mailing address as on the Standard Chartered Bank records. The customer is expected to receive the consignment at the mailing address. Standard Chartered Bank is not liable for loss or damage of goods in case of the customer not being available in person to receive the gift article Redemption orders from Standard Chartered Platinum Elite Cardmembers once given to Standard Chartered Bank cannot be cancelled or withdrawn or changed On redemption, the reward points would automatically be subtracted from the accumulated points in the Standard Chartered Cardmember account Goods will reach the Primary Cardmember within 4-6 weeks of receipt of the order on a best effort basis. Notwithstanding the same, Standard Chartered Bank will not be held liable for any delay beyond this time period All products / vouchers are subject to availability and will be allocated on a first-come-first-served basis Orders will be fulfilled in the order in which they are received and accepted by Standard Chartered Bank Cardmember is solely responsible for any govt tax, duties or other charges imposed by law in any country in respect of the programme, participation in the programme and any points converted or acquired or any other transaction within the programme Pictures or any artwork shown in the Platinum Indulgence Rewards catalogue is only indicative of the rewards. Actual reward may vary This agreement is only for participation in Standard Chartered Platinum Indulgence Reward programme and does not in any way waive, amend or override any of the Terms and Conditions of the existing Cardmember agreement with Standard Chartered Bank. All such Cardmember Terms and Conditions continue to remain in full force To avail the holiday at Cliveden House Cardmember would have to intimate Standard Chartered Bank atleast 3 months in advance and is subject to availability
DEH-P8000R P2B98XV DVD-HR730 Blade HT-DDW750 S5000 DT 250 GR-S392QVC Mitsubishi P93 Price XBM1228 SL3242FX-PRO Laserjet 2400 Sunbeam 2346 CDX-GT430U EWF1435 MZ-E25 WFM-90 PRO 9500 SC-PM32DB GK1000 RD-100 40006 Satellite A70 GN 9330 HT-IS100 Velo 8 Psae0 630-CI Citroen C1 REX T6 Asus P5QC AX-5103 KX-P2130 DSC-W150 B Watch B873 Playstation 3 LE46F86BD WD3200H1q-00 GR-282MF Digital Camera ER-2301 312SC WIL 125 DSC-T7 Supplement WD 7105 MHC-RG66T Joybee 125 LE40M5 Q1435V Dmczs7 Phone FW-C700 34 SGH-E420 T4350 Realis SX60 TNT100-120 MS7157C NC2400 Memory Card RL44ecps P-3000 Drivers FWD-40LX2F Series 8001 E Trap BO4901 MC-8084NLC Tx9000A OT-E157 M430TR Auto 2 Carlo MP34 CQ-C9800N LE23R86WD SX-AX7 TX-36PL35P Photosmart M437 User Guide MS8147C Alert 2 Instructions Simon 3000V PDP-615EX Pp4018 RP-201 DS607 60 CT-4 MDR-ED12LP BKF 404 VF2058 CDX-FM657 LA32C350 VP-9000 FDS200 DSC-F1 DMX-50 DES-3018 Taiwan Battery DEH-P9650MP Software Download Review SF-505 Cisco 7941 ICF-CD855 TS-WX22 | http://www.ps2netdrivers.net/manual/canon.powershot.a450/ | CC-MAIN-2013-20 | refinedweb | 6,078 | 60.75 |
[truelocal.com.au...]
Compare to the orginal TrueLocal:
[truelocal.com...]
According to some info WebmasterWorld has obtained, News Corp *was* aware of TrueLocal.coms existence prior to the aussie launch. News corp would not respond to requests for an interview.
I'm guessing copyright laws, name registration laws, and other issues will arise because of this.
SMH an Australian news company has written an article about this conflict titled will the real truelocal please stand up.
if forced
A court might decide that True Local took no steps to protect the name in Australia and therefore, deserves no protection. I'm sure it won't be hard to find attorneys that make compelling arguments for both sides. Give 'em hell Jake.
>>hundreds of Australians" have already attempted to sign up to its service after mistaking it for the recently launched directory listing service from News Ltd.
Lol. This is the biggest reason why this was a mistake on the Aussie's part. Anyone recall BakeJake's presentation in Vegas on 101 twisted things to do to people you don't really want at your website? I'd be surprised if they had a case legally, but even if they pull that off somehow, they've still got to worry about the online side of things.
(*)I'm thinking if Jake captures australian traffic and send them to <some funky> site, that'll do some interesting things to folks looking to advertise on the .au site who mistyped.
[edited by: tedster at 6:42 pm (utc) on Feb. 2, 2006]
This truelocal seems to contain the same data...
Good news for all who paid top dollar to be listed.
One of the 3 national TV stations has become part of Yahoo Australia (one of the others is part of MSN in Australia).
With such a small population and cross media ownership laws... some big media companies don't seem to like others (personally, I can't keep track of who's who).
But both 'truelocal' & the Yahoo/TV station happened at the same time.
I don't really see their USP?
(all 'compared to' stuff above relates to the AU yellow pages)
Aside from any copyright issues relating to the web site design itself, I would say the truelocal.com owners have very little grounds for complaint. News Limited have a genuine claim to the .com.au version of the domain name, based on what their site offers. This namespace is more restricted than some others but it is still on a first come, first served basis.
They have also submitted trademark applications to protect the name/logo, so you could say they were well prepared. | http://www.webmasterworld.com/forum10/10851.htm | CC-MAIN-2014-15 | refinedweb | 445 | 73.58 |
Hello 世界!
Hello hello! For better or worse, you have landed on my inaugural post on this blog. It's exciting to have a blank canvas to profane with my thoughts. Let's start with how I built this site.
The Process
It was nice to flex my right brain and design for this project, since I was a developer at my last job. My process was as follows:
- Draw notepad sketches for layout ideas
- Prototype website in the browser
- Draw assets with my Wacom or take pictures with my Canon
- Code up a static site generator to organize the project
- Create the deployment scripts.
Afterwards, I wrapped the HTML prototype with a site generator to generate the other pages. Finally, I wrote two simple bash scripts to upload my homepage to Github Pages and the blog to Google Cloud Storage.
Technical Details
Feel free to skip ahead to the next section if you're not interested in the techie nitty gritty :)
Both my homepage and blog are based on the static generator described by Nicolas Parriault here. In addition to his basic generator, I added webassets for asset compilation, an Atom feed generator, and an html minifier. I'll skip the basic generator that Nicolas describes and talk about the additions.
On the front end I wanted to separate my javascript files by logic and wanted to minimize asset size to provide readers a speedy experience. To that end, I used webassets because I was familiar with it and the htmlmin package (django-htmlmin was choking on Chinese characters).
from flask.ext.assets import Environment, Bundle assets = Environment(app) assets.load_path = ["source"] assets.cache = ".webassets-cache" # Webasset Bundles styles = Bundle( "scss/styles.scss", filters="scss", output="css/styles.css") js = Bundle( "js/main.js", "js/more.js", filters="closure_js", output="js/main.js") assets.register("styles", styles) assets.register("js", js)
For htmlmin, I wrote a small helper function that renders the template without minification during debug but minifies during builds.
from htmlmin import minify # Helpers def render(*args, **kwargs): if is_build: return minify(render_template(*args, **kwargs)) return render_template(*args, **kwargs)
I also wanted a feed and found the feedgen package which provides a FeedGenerator class. The code is pretty straight forward although I had to read up on the Atom spec.
@app.route("/feed/") def feed(): feed = FeedGenerator() feed.id("blog.yoursite.com") feed.title("Your Blog\'s Feed") feed.author(dict(name="Your Name", email="your-email@gmail.com")) feed.logo("cdn.com/your-logo.png") feed.subtitle("Description of your blog") feed.link(href="") feed.language("en") for page in pages: page_url = "" % ("blog.yoursite.com", url_for("page", path=page.path)) feed_entry = feed.add_entry() feed_entry.id(page_url) feed_entry.title(page.meta["title"]) feed_entry.link(href=page_url) publish_date = pacific_timezone.localize( datetime.strptime(page.meta["date"], "%B %d, %Y")) feed_entry.published(publish_date) feed_entry.content(page.html) return (feed.atom_str(pretty=True), 200, {"Content-Type": "application/atom+xml"})
Bonus! Flatpages also comes with pygment support for those who code.
from flask_flatpages import pygments_style_defs @app.route("/pygments.css") def pygments_css(): return (pygments_style_defs("monokai"), 200, {"Content-Type": "text/css"})
For the deployment scripts, Nicolas' static site generator uses Flask-FlatPages to create a static build in a build folder so I just
git push the build folder for my homepage and
rsync my blog to Google Cloud Storage.
Ante up!
The point of this blog is to improve my writing and share my projects with others. I learn best when I jump off the proverbial cliff and start doing. From feedback from you, my writing will naturally improve! ☺ It will also be interesting to see how my projects evolve from people's input. I intend on blogging about:
- Startups
- Investing
- Languages
- Art – photography, drawing, design
- And more?
So pick a topic you enjoy and stay tuned! 再見。 | http://blog.michaelsu.io/hello-world/index.html | CC-MAIN-2018-22 | refinedweb | 635 | 50.12 |
Fabulous Adventures In Coding
Eric Lippert is a principal developer on the C# compiler team. Learn more about Eric.
Yet another amusing question from StackOverflow: is there a difference between “return something;” and “return (something);” in C#?
In practice, there is no difference.
In theory there could be a difference. There are three interesting points in the C# specification where this could present a problem.
First, conversion of anonymous functions to delegate types and expression trees. Consider the following:
Func<int> F1() { return ()=>1; } Func<int> F2() { return (()=>1); }
Func<int> F1() { return ()=>1; } Func<int> F2() { return (()=>1); }
F1 is clearly legal. Is F2? Technically, no. The spec says in section 6.5 that there is a conversion from a lambda expression to a compatible delegate type. Is that a lambda expression? No. It's a parenthesized expression that contains a lambda expression.
The compiler makes a small spec violation here and discards the parenthesis for you.
Second:
int M() { return 1; } Func<int> F3() { return M; } Func<int> F4() { return (M); }
int M() { return 1; } Func<int> F3() { return M; } Func<int> F4() { return (M); }
F3 is legal. Is F4? No. Section 7.5.3 states that a parenthesized expression may not contain a method group. Again, for your convenience we (accidentally!) violate the specification and allow the conversion.
Third:
enum E { None } E F5() { return 0; } E F6() { return (0); }
enum E { None } E F5() { return 0; } E F6() { return (0); }
F5 is legal. Is F6? No. The spec states that there is a conversion from the literal zero to any enumerated type. "(0)" is not the literal zero, it is a parenthesis followed by the literal zero, followed by a parenthesis. We violate the specification here and actually allow any compile time constant expression equal to zero, and not just literal zero.
So in every case, we allow you to get away with it, even though technically doing so is illegal.
Is there any reason other than convenience that was the spec violated?
The spec was not violated deliberately in order to be more convenient; these were all bugs. The semantic analyzer throws away the "meaningless" parentheses. -- Eric
Will this ever be "fixed" introducing breaking changes?
Hopefully not. We try to only introduce breaking changes when there is a clear benefit to doing so. -- Eric
Basically what I'm getting at is, is it better to avoid those scenarios.
Yes. -- Eric
What are the odds that the spec will be updated to match the compiler's actual behavior?
Very low. -- Eric
I for one am glad that the spec was violated here. When you're programming you shouldn't be fighting the grammar (as is often the case in C++); you should be focused on solving the problem at hand.
Since the implemented behavior is clearly the desirable behavior I'm curious as to the answer to your question also Stuart. I also wonder if Mono deviates from the spec to provide these services...
You'll have to ask someone who is an expert on Mono. Or try it yourself. I wouldn't know. -- Eric
Is there any chance the spec will be updated to reflect the more-desirable behavior?
@blodbath: Mono appears to follow .NET here: all of the methods in this blog entry compile without error under gmcs from Mono 2.4 and current trunk.
I would have thought the current compiler behavior existed for the sake of consistency, as the parentheses are required when casting a lambda to a delegate type.
"(Action)() => DoSomething()" is not legal, but "(Action)(() => DoSomething())" is.
I agree with Mike, though I really don't understand why that cast isn't implicit.
@mattzink Primarily, the cast can't be implicit because there could be any number of matching delegate types, and the compiler doesn't know which version to use. For example, Action, CrossAppDomainDelegate, and ThreadStart all have the same prototype (no return type, no arguments). Which should the compiler choose?.
@Jonathan: They "sort of" did provide a "default" delegate type: System.Delegate. This is used in a few places to accept "any" delegate, i.e. in WPF's Dispatcher.Invoke() APIs. However, the value you provide must have a concrete delegate type (e.g. you must cast it, construct a new delegate, or pass in an explicitly-typed member or variable).
I wonder why the specfication was written like this in the first place.
>.
Because Action/Func didn't appear until .NET 3.5, I guess.
> Because Action/Func didn't appear until .NET 3.5, I guess.
And because Action/Func only cover, what, up to 4 method arguments? Actually, I just looked in the spec and couldn't find an upper limit. Seems like Eric's mentioned one semi-recently, that's actually been encountered in the field (via codegen), but I couldn't find that either. Not my day for research skills.
<i>Is</i> there a limit in the spec, or is that an implementation detail?
Clarifying last question: is there a limit on the number of formal arguments a method can have? Not asking if there's a spec on Action/Func.
I do not know of any restriction in C# or in the CLI on the number of formal parameters or generic type parameters. We've tested generic types with hundreds of generic type parameters with no problems. (Of course, methods or types with more than a handful of parameters are a bad idea anyway.) -- Eric
Thanks! E. Lippert 1, Google 0.
Apropos of nothing, I'd like to request that you never change your tag scheme to include anything that comes alphabetically after "What's The Difference?" Every time I visit, I look at the tag cloud and enjoy the conclusion:
What's The Difference? Zombies
If you ever have a need to print T-shirts--perhaps in support of a North American tour?--you could do worse than putting that on them.
> And because Action/Func only cover, what, up to 4 method arguments?
It was 4 in .NET 3.5 (which was just enough to account for all extension methods in Enumerable). It's up to 16 in .NET 4 (e.g. see).
> Actually, I just looked in the spec and couldn't find an upper limit.
The limit on number of template parameters is not directly relevant here, because neither Func nor Action are "magic" types - they are just normal generic delegate types manually declared in System.Core.dll, like so:
delegate void Action();
delegate void Action<T1>(T1 arg1);
delegate void Action<T1, T2>(T1 arg1, T2 arg2);
...
Consequently, the only thing that matters here is however many parameters the library designers have decided to stop at.
Anyway, there is no explicit constraint in the CLR spec on number of type parameters. As for implicit constraints - their definitions are referenced in the metadata tables via int32 indices. | http://blogs.msdn.com/b/ericlippert/archive/2010/04/12/ignoring-parentheses.aspx | CC-MAIN-2014-52 | refinedweb | 1,150 | 66.54 |
Break out of input after interrupt
Hi,
I'm using input to have the user input something. If the button is pressed (using the expansion board) the input should be interrupted and some other code should be executed. This almost work:
state = 1
handler for interrupt
def interrupthandler(pin):
print('interruption detected')
global state
state = 2
initialize GP17 in gpio mode and make it an input with the pull-up enabled
button=Pin('G17',mode=Pin.IN, pull=Pin.PULL_UP)
button.callback(trigger=Pin.IRQ_FALLING, handler=interrupthandler)
while True:
if state == 1:
input("Give me an input: ")
elif state == 2: print("We've been interrupted") state = 1
I do get into the interrupthandler, however when the code continues it still waits for the user input. If i press anything+enter the code continues into state 2 and back to state 1 as expected. How can I automatically break out of the input prompt after the interrupt?
Thanks!
edit: Sorry for the formatting - I dont know how to get it right..
@robert-hh Thanks! Yeah I can do some stuff in the handler, but as far as I can understand it is recommended to keep the handler short and effective. In this case I would like to transmit (LoRaWAN), receive some data etc.
Anyway - thanks for the help - I'll figure something out. :)
@mahe I looked a little bit though the code yetserday, and I found no place to force abort an input statement.
But the interrupt happens and the interrupt handler gets control. If you just want to do soemthing and then return to the input, then you can do that in the interrupt handler.
Otherwise, you have to implement your one busy waiting input function, which checks to interrupt events being noticed. But that's not elegant and would cover only a single use case.
@peekay123 @robert-hh Thats correct, sorry if the question was unclear. The problem is that the interrupt handler does not break the 'input-state' (or whatever it's called) and move into state 2. I also looked a bit at try/except, but couldn't figure out how to throw an exception..
This is my first venture into Python, so it's all very new to me. I've been looking a bit at threading, maybe that's a possibility.. Anyways - thanks for the effort!
@peekay123 As far as I understand, this is not the intention of @mahe. He wants the input statement to be interrupted by the external button.
I will check later, if raising a KeyboardInterrupt in the ISR may do the trick. It may not, since there is still a bug in the formware in that KeyboardInterupts are not serviced timely in all circumstances. If yes, the input statement has to be gated by a try/except clause.
Edit: That does not work. The main code still sits in the line edit state of the input statement.
@mahe, you answered you own question when you say:
"If i press anything+enter the code continues into state 2 and back to state 1 as expected"
So set state = 3 instead of 1 so that the code continues. When you are ready for input again, set state = 1 again. | https://forum.pycom.io/topic/1825/break-out-of-input-after-interrupt | CC-MAIN-2018-39 | refinedweb | 536 | 71.34 |
WL#9141: InnoDB: Refactor uncompressed BLOB code to facilitate partial fetch/update
Affects: Server-8.0 — Status: Complete
Introduction: ============= This is a sub worklog of "WL#8960 InnoDB: Partial Fetch and Update of BLOB". This worklog is the second sub worklog followed by "WL#8985 InnoDB: Refactor compressed BLOB code to facilitate partial fetch/update". The purpose of this worklog is to refactor current code so that new BLOB features can be added conveniently. This worklog does to uncompressed BLOB similar to what WL#8985 did to compressed BLOB code. Logical Changes: ================ . The functionality of uncompressed BLOB is provided by C-style functions. This will be converted to C++ classes, structs and member functions. . The BLOB code will be isolated and kept in lob0lob.h and lob0lob.cc files. This will help in modular development of BLOB features. . All references will now be LOB (large objects). Detailed Changes: ================= . Introduced new module named lob. It contains lob/lob0lob.cc and include/lob0lob.h files. . Added new namespace lob. . lob::Inserter - a new class to insert a complete uncompressed BLOB. . lob::zInserter - a new class to insert a complete compressed BLOB. . lob::InsertContext - a new class to contain contextual information for the insert operation. . lob::BaseInserter - a class that holds common state and functions useful for both compressed and uncompressed BLOB. This is the base class for lob::Inserter and lob::zInserter. . lob::Deleter - a new class to destory/delete a BLOB (both compressed/uncompressed) . lob::DeleteContext - a new class to contain contextual information for the delete operation . lob::Reader - a new class to fetch a uncompressed BLOB. . lob::zReader - a new class to fetch a compressed BLOB. . lob::ReaderContext - a new class to contain contextual information for the fetch operation Design Rationale: ================= There are 2 approaches that I explored - one is to have a single LOB class with each major operations as an member function. For example, class LOB { public: int insert(); int update(); int read(); // .. private: // ... Context* m_ctx; }; But doing it this way, will make the class LOB like a kitchen sink. It will end up that some member variables are used only when we are doing insert operation, and some other member variables are used when doing read operation and so on. There won't be any cohesion b/w the member variables and member functions. For one instance of the LOB class, we will most likely use only one operation, eg insert. This is the reason I didn't prefer this approach. The other approach is to design LOB classes around the major operations that will be performed, which truely reflects the way these classes will be used. The current design of LOB classes revolves around the way the major operations that will be performed on LOB data. The currently supported major operations are insert, delete and read. As of now all of them operate on complete LOB data. For each of the major operation one new class is introduced. Inserter - for inserting LOB data. Reader - for reading LOB data. Deleter - for deleting LOB data. Now there are two variants to LOB data - compressed and uncompressed. An insert operation or a read operation is completely depended on whether the data is compressed or not. But a delete operation is not that much dependant on this. Hence I introduced separate classes for compressed LOB. Inserter - for inserting uncompressed LOB data. zInserter - for inserting compressed LOB data. Reader - for reading uncompressed LOB data. zReader - for reading compressed LOB data. Deleter - for deleting both compressed and uncompressed LOB data. At this point I noticed that there was some common code between Inserter and zInserter which I can factor out into a base class. So I introduced BaseInserter which will contain common state and function useful for both Inserter and zInserter. So the final list of main LOB classes are: Inserter - for inserting uncompressed LOB data. zInserter - for inserting compressed LOB data. BaseInserter - a base class containing common state and functions useful for both Inserter and zInserter. Inserter and zInserter derives from this base class. Reader - for reading uncompressed LOB data. zReader - for reading compressed LOB data. Deleter - for deleting both compressed and uncompressed LOB data. One point to be noted is that these classes are formed by refactoring existing code. So to reduce the amount of code changes, I allowed some differences in the way they operate. The Inserter and zInserter class is designed to insert all the LOB data of a single clustered index record. It operates on the big record vector. But the other classes (Reader, Deleter, zReader) all operate on a single LOB data only. By doing it this way, I avoid significant amount of code changes. The main classes of the LOB module has been identified above. To support them there was a need to provide context classes that will contain information needed for LOB operation. Previously, the C style functions had a list of 6 or 7 arguments. These arguments are the context information that is necessary to provide the various main operations on LOB data. For each main operation, the context information is identified separately. They are as follows: InsertContext - context information for doing insert of LOB. ` DeleteContext - context information for doing delete of LOB. ` ReadContext - context information for doing fetch of LOB. ` The insert operation also has one special optimization - the bulk insert. These context classes evolved separately as I refactored one operation at a time. And when I look back, I don't see any need to club them all together. There are some specific checks that are done only for the insert operation, like the redo log space check, which are captured in the InsertContext. If we have a single context class, then it will contain unnecessary information not usable for the current operation. Also, all these context classes are arrived at based on how and where it will be used. Finally, while evaluating this design, please do keep in mind that these classes come out of refactoring existing code. If you look at the patch, the amount of code changed where LOB module is _used_ is very minimal. I think my main focus was to isolate the LOB code and design a set of C++ classes which will make the extension of functionality easier. And the main purpose of refactoring was to enable to add partial fetch and partial modify/update operations. For these purposes, I believe that this design is suitable. Surely one can do more and more refactoring to achieve better results. But since we are doing refactoring for a particular purpose, I think we should stop when our purpose will be solved. Functions Removed: ================== The following functions has been removed. . btr_copy_blob_prefix() . btr_copy_externally_stored_field_prefix_low_func() Functions Moved to lob module: ============================== The following functions are moved to the lob module. . btr_copy_externally_stored_field_prefix_func() and the associated macros. . btr_rec_free_updated_extern_fields() . btr_blob_get_part_len() . btr_blob_get_next_page_no() . btr_check_blob_fil_page_type() . btr_rec_free_externally_stored_fields() . btr_copy_externally_stored_field_prefix_func() . btr_copy_externally_stored_field_func()
There is no functionality changes done in this worklog. There are no functional and non-functional requirements. Just ensure that there are no performance regressions because of this code refactoring.
This worklog will isolate the LOB code into a separate module. The following will be the interface to make use of LOB. lob::Inserter - a class to insert uncompressed large object (LOB). lob::Reader - a class to fetch uncompressed LOB. lob::Deleter - a class to free/delete both compressed/uncompressed LOB. lob::zInserter - a class to insert compressed LOB. lob::zReader - a class to fetch compressed LOB. For each of the LOB operations described above there is an associated context object. They are listed here: lob::InserterContext - a context object for insert operation. lob::ReaderContext - a context object for fetch/read operation. lob::DeleterContext - a context object for delete/free operation. A new namespace lob has been introduced that enclose all large object (LOB) classes, structs, enums and functions.
Copyright (c) 2000, 2021, Oracle Corporation and/or its affiliates. All rights reserved. | https://dev.mysql.com/worklog/task/?id=9141 | CC-MAIN-2021-10 | refinedweb | 1,312 | 59.09 |
I’ve received a few requests regarding manual installation of Slim Framework. Although I prefer using Composer, many people have issues when installing on remote hosts. The following post provides a short description on manual installation of Slim framework.
1. First download the Slim zip archive from github –
2. Extract from the archive and copy the Slim directory to your
public_html directory or wherever you need to install. Note that there are a couple of nested sub-directories named slim. Copy the one that has the ‘Slim.php’ file in it.
3. Copy the following test code to a file named
hello.php
4. In your browser navigate to the URL, where example.com represents your domain name, this could even be your localhost. You should see ‘Hello, world! Welcome to Slim Framework’ in the browser.
Note that the example assumes that you uploaded the Slim Framework to the public_html directory, which contains the Slim subdirectory. If you uploaded the Slim Framework to some other directory make sure that you change the ‘require’ statement accordingly. For example if you installed it in ‘frameworks’ subdirectory change the ‘require’ to the following.
require ‘frameworks/Slim/Slim.php';
The main thing to take notice is of
Slim::registerAutoloader(), which handles all the autoloading of classes. When you instead use Composer to install the framework the ‘autoload.php’ file installed by Composer takes care of the autoloading.
You can add the PHP
use keyword to change the namespace of the code. This will allow you to import the ‘Slim/Slim’ namespace in the current code context and hence drop the namespace prefixes before method names.
Hope this helps in performing a manual installation of Slim framework.
Nice description with good ratio of code and explanation. Thx! | http://www.codediesel.com/php/how-to-manually-install-slim-framework/ | CC-MAIN-2017-04 | refinedweb | 292 | 59.09 |
sample data in a clip.
The samples should be floats ranging from -1.0f to 1.0f (exceeding these limits will lead to artifacts and undefined behaviour).
The sample count is determined by the length of the float array.
Use offsetSamples to write into a random position in the clip. If the length from the offset is longer than the clip length, the write will wrap around
and write the remaining samples from the start of the clip.
Note that for compressed audio, the sample data can only be set when the Load Type is set to Decompress on Load in the audio importer.
using UnityEngine;
public class Example : MonoBehaviour { // Read all the samples from the clip and half the gain void Start() { AudioSource audioSource = GetComponent<AudioSource>(); float[] samples = new float[audioSource.clip.samples * audioSource.clip.channels]; audioSource.clip.GetData(samples, 0);
for (int i = 0; i < samples.Length; ++i) { samples[i] = samples[i] * 0.5f; }
audioSource.clip.SetData(samples, 0); } }
Did you find this page useful? Please give it a rating: | https://docs.unity3d.com/ScriptReference/AudioClip.SetData.html | CC-MAIN-2019-51 | refinedweb | 172 | 67.96 |
Am 08.05.2012 21:42, schrieb Alexander Graf: > > On 08.05.2012, at 21:29, Andreas Färber wrote: > >> On patch 3/3 he didn't like my alignment macro. I don't have a better >> one though, suggestions or patches welcome. Ideal might be some >> ROUND_TO_ODD() macro, but the problem is that for Darwin/AIX where it's >> no-op it shouldn't result in a "statement without effect" warning. >> Therefore my do { } while (0) as opposed to ir = MACRO(ir). > > static inline int round_reg_i64(int input_reg) > { > #ifdef WHATEVER_CONDITION > if (input_reg % 2) { > reg++; > } > #endif > > return reg; > } > > [...] > > ir = round_reg_i64(ir); I think he didn't like the mod check either but the suggestion <malc> [...] reg += reg & TCG_TARGET_CALL_ALIGN_ARGS [...] doesn't work well when TCG_TARGET_CALL_ALIGN_ARGS is undefined. And defining it with value 0 seems unsafe to me. What about the following? (untested) static inline int tcg_target_call_align_i64_reg(int reg) { #ifdef TCG_TARGET_CALL_ALIGN_ARGS /* Round up to next odd register */ return (reg & ~1) + 1; #else return reg; #endif } Andreas -- SUSE LINUX Products GmbH, Maxfeldstr. 5, 90409 Nürnberg, Germany GF: Jeff Hawn, Jennifer Guild, Felix Imendörffer; HRB 16746 AG Nürnberg | http://lists.gnu.org/archive/html/qemu-devel/2012-05/msg01040.html | CC-MAIN-2015-14 | refinedweb | 183 | 67.15 |
On Mon, 2007-02-05 at 18:13 -0800, Andreas Gruenbacher wrote:> On Monday 05 February 2007 10:44, Christoph Hellwig wrote:> >.> > It may appear like laziness, but it's not. Let's look at where we're passing > NULL at the moment:> > fs/hpfs/namei.c> > In hpfs_unlink, hpfs truncates one of its own inodes through> notify_change(). You definitely don't want any lsms to interfere here,> pathname based or not; hpfs should probably truncate its inode itself> instead. But given that hpfs goes via the vfs, we at least pass NULL> to indicate that this file really has no meaningful paths to it> anymore. (In addition, we don't really have a vfsmount at this> point anymore, and neither would it make sense to pass it there.)> > To play more nicely with other lsms, hpfs could mark the inode as> private before attempting the truncate.> > fs/reiserfs/xattr.c> > The directories an files that reiserfs uses internally to store xattrs> are hanging off ".reiserfs_priv/xattrs" in the filesystem. This part> of the namespace is not accessible or visible from user space though> except through the xattr syscalls.> > Reiserfs should probably just mark all its xattr inodes as private in order> to play nicely with other lsms. As far as pathname based lsms are concerned,> pathnames to those fs-internal objects are meaningless though, and so we> pass NULL here.That should be handled by the current marking of reiserfs xattr inodeswith S_PRIVATE and the tests for IS_PRIVATE in include/linux/security.h(and in one instance, within SELinux itself).-- Stephen SmalleyNational Security Agency-To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at | https://lkml.org/lkml/2007/2/6/128 | CC-MAIN-2018-39 | refinedweb | 293 | 55.64 |
Design patterns for flask API implementation
I am using flask with flask-restplus and sqlalchemy.
My rest API function looks like the following:
@ns.route('/user') class UsersCollection(Resource): @jwt_optional @permissions.user_has('admin_view') @ns.marshal_list_with(user_details) def get(self): """ Returns list of users. """ users = User.query.all() return users
I am willing to add additional data to
users collection which should be returned by the API. Some of this data may be stored in other DB tables, while other is stored in memory.
What I am usually doing is something like this:
@ns.route('/user') class UsersCollection(Resource): @jwt_optional @permissions.user_has('admin_view') @ns.marshal_list_with(user_details) def get(self): """ Returns list of users. """ users = User.query.all() # Add additional data for user in users: user.activity = UserActivity.query ... # from DB user.online_status = "Active" # Taken somewhere from memory return users
Obviously I don't like this approach of adding data to the User object on the fly. But what is the best design pattern to achieve it?
See also questions close to this topic
- python to print item in list from a json post
i'm running Python 3.7 Flask RestFul I have data being post in json format to my api Flask app. the data i receive looks like the below
{'username': 'admin', 'password': 'mypassword', 'host': [{'address': '192.168.2.5'}, {'config': 'set system host-name device01'}, {'address': '192.168.2.2'}, {'config': 'set system host-name device02'}]}
the List 'host': can be up to several hundred devices / ip address
I need to parse thru the list and print out only the IP address and Config so i need to get it to be 192.168.2.5 192.168.2.2 and so on.... so i can loop thru the IP address list and connect to device and apply the config that will be different per device.
my python code is below...
data = request.get_json(force=True) print(data) username = data['username'] password = data['password'] iplist = data['host'][2] for host in iplist: #host = host.split() print(iplist) ip = iplist #break conf = data['host'] for config in conf: #config = config.split() #print(conf) load = conf #break #dev = Device(host=ip, user=username, passwd=password) #dev.open() #print("connect to %s " % ip) #dev.timeout = 600 #dev.bind(cfg=Config) #dev.cfg.load(load, format='set', merge=True) #dev.cfg.commit() #dev.close() break
- Python raw HTML contain "\n" characters that i cannot remove with the replace command
I am getting HTML data with a python get( url ) command which returns raw HTML data that contains “\n” characters. When I run the replace (“\n”,””) command against this it does not remove it. Could some explain how to either remove this at the "simple_get" stage or from the "raw_htmlB" stage! Code below.
from CodeB import simple_get htmlPath = "" raw_html = simple_get(htmlPath) if raw_html is None: print("not found") else: tmpHtml = str(raw_html) tmpHtmlB = tmpHtml.replace("\n","") print("tmpHtmlB:=", tmpHtmlB) from requests import get from requests.exceptions import RequestException from contextlib import closing from bs4 import BeautifulSoup def simple_get(url): try: with closing(get(url, stream=True)) as resp: if is_good_response(resp): return resp.content else: return None except RequestException as e: log_error('Error during requests to {0} : {1}'.format(url, str(e))) return None def is_good_response(resp): content_type = resp.headers['Content-Type'].lower() return (resp.status_code == 200 and content_type is not None and content_type.find('html') > -1) def log_error(e): print(e)
- python regex conditional in re.sub - how?
Is it possible to use python's regex conditionals in
re.sub()? I've tried a number of variations without luck. Here's what I have.
import re # match anything: <test> always true a = re.compile('(?P<test>.*)') # return _'yes'_ or 'no' based on <test> a.sub('(?(\g<test>)yes|no)', 'word') '(?(word)yes|no)'
I expected either a 'yes' or 'no,' not the actual test.
What I get from this is that
<test>is seen but the regex conditional isn't being executed. Is there another way of accomplishing this?
I tried with
re.sub(pat, rep, str)with same results.
-.
- API isn't called when first logged in
I'm trying to call my API from code behind when I submit an order. I first login using Active Directory and have it transfer to my order submission page after a successful login. When I submit the order, the code doesn't call my API and moves on. When I restart, I don't have to login again, just sent to the order submission page and when I submit my order this time, the API gets called and everything works fine. I feel like I've ran into this before. Has anyone ever had this issue or know how to fix it?
Dim request As HttpWebRequest request = CType(WebRequest.Create(apiUrl), HttpWebRequest) request.Method = "GET" request.ContentType = "text/xml" request.UseDefaultCredentials = True request.PreAuthenticate = True request.Credentials = CredentialCache.DefaultCredentials Dim respond As HttpWebResponse = CType(request.GetResponse, HttpWebResponse)
The call happens at my HttpWebResponse.
- How to use TFS REST API for making changes to work item as specified user
I need something like Make Changes to a TFS Work Item as a specific user but for TFS REST API.
So:
new WorkItemTrackingHttpClient(new Uri(""), new VssCredentials(...));
what are my next steps?
- Do I need two instances of python-flask?
I am building a web-app. One part of the app calls a function that starts a tweepy StreamListener on certain track. That functions process a tweet and then it writes a json object to a file or mongodb.
On the other hand I need a process that is reading the file or mongodb and paginates the tweet if some property is in it. The thing is that I don't know how to do that second part. Do I need different threads? What solutions could there be?
- How to implement a cache system using Celery and Flask
I am implementing an online server using:
Flask
NGINX
Celery
Celery uses:
RabbitMQas a broker
Redisas a Result backend.
I would know if it is possible to use
Redisas a cache to avoid doing big calculations if I receive the same request. For example, I want to answer a cache result if I receive a
POSTcontaining the same body.
If it is possible, do I have to configure it in Celery or in Redis? And how should I do it?
- creating and appending to a list in SQLAlchemy database table
I am learning SQLAlchemy and I am stuck. I have a SQL table (table1) has two fields: 'name' and 'other_names'
I have an excel file with two columns:
first_name alias paul patrick john joe simon simone john joey john jo
I want to read the excel file into my table1, so that it looks like this (i.e. all of the aliases for the same line are on one row):
paul patrick john joe,joey,jo simon simone
This is the idea that I was trying to do. The code (with comments) that I tried:
for line in open('file.txt', 'r'): #for each line in the excel file line = line.strip().split('\t') #split each line with a name and alias first_name = line[0] #first name is the name before the tab alias = line[1] #alias is the name after the tab instance = Session.query(session,tbs['table1'].name).filter_by(name=first_name) #look through the database table, by name field, and see if the first name is there list_instance = [x[0] for x in instance] #make a list of first names already in database table if first_name not in list_instance: #if the excel first name is not in the database table alias_list = [] #make an empty list alias_list.append(alias) #append the alias name_obj = lib.get_or_create( #small function to make db object session, tbs["table1"], name = first_name, #add first name to the name field other_names = alias_list # add alias list to the other_names field ) elif first_name in list_instance: #elif first name already in db alias_list.append(alias) #append the alias to the alias list made above name_obj = lib.get_or_create( session, tbs["table1"], name = first_name, other_names = alias_list #create object as before, but use updated alias list )
The problem is that I can get the above code to run with no errors, but also the output is not an appended list, it is simply a database table that looks like the excel file; i.e.
name alias paul patrick john joe simon simone john joey john jo
Could someone point out where I am going wrong, specifically, how do i amend this code? Please let me know if the question is unclear, I've tried to make it a simple example. Specifically, how do I initialise and add to lists as a field entry in a SQLalchemy db table.
- How to target PostgreSQL schema in SQLAlchemy DB URI?
I understand that I can set
search_pathfor the db role used to log in, but is there a way to specify the schema at the URI level or something to that effect? I may be mistaken due to my PostgreSQL experience being only with the JDBC driver.
My current URI fails:
postgresql://app_user:pw@localhost/dev_db?currentSchema=app
psycopg2is complaining about
currentSchemabeing an invalid option
sqlalchemy.exc.ProgrammingError: (psycopg2.ProgrammingError) invalid dsn: invalid connection option "currentSchema" (Background on this error at:)
- Is there any way set __bind_key__ of Flask SQLAlchemy's Model to be dynamic
I have mutiple binds of database, I want to set the bind_key by diferent query params.
- Flask Restplus return columns join query
I have two models that relate to each other. I want to make an inner join between the two models and return it in a specific path. The problem is that the disc only accepts the columns of a single model. Sorry for the bad writing. I want all Fields by ProcedureType.id, something like SELECT pt.name, pt.description, f.* FROM proceduretype pt INNER JOIN field f ON pt.id = f.procedure_type_id WHERE pt.id = 1. I attach the code.
Model ProcedureType
class ProcedureType(db.Model): id = db.Column(db.Integer, primary_key=True, autoincrement=True) dependence_id = db.Column(db.Integer) name = db.Column(db.String(100)) description = db.Column(db.String(500)) requirements = db.Column(db.String(500)) online = db.Column(db.Boolean, default=False) def __init__(self, dependence_id, name, description, requirements, online): self.dependence_id = dependence_id self.name = name self.description = description self.requirements = requirements self.online = online
Model Field
class Field(db.Model): id = db.Column(db.BigInteger, primary_key=True, autoincrement=True) procedure_type_id = db.Column(db.Integer, db.ForeignKey( ProcedureType.id), nullable=False) name = db.Column(db.String(50), nullable=False, unique=True) label = db.Column(db.String(100)) type = db.Column(db.String(100)) default_value = db.Column(db.String(100)) validations = db.Column(db.JSON) def __init__(self, procedure_type_id, name, label, type, default_value, validations): self.procedure_type_id = procedure_type_id self.name = name self.label = label self.type = type self.default_value = default_value self.validations = validations
service.py
def prueba_inner_join(id): return db.session.query(Field).join(ProcedureType).filter_by(id=id)
Controller
from flask import request from flask_restplus import Resource from .dto import ProcedureTypeDto, FieldDto from . import service field_ns = FieldDto.api _field = FieldDto.field_procedure @field_ns.route('/<id>') class FieldList(Resource): @field_ns.doc('procedure_type') @field_ns.marshal_list_with(_field) def get(self, id): """List all procedure types""" return service.get_fields_procedure(id)
DTO
class FieldDto: api = Namespace('field', description='Field related operations') field_procedure = api.model('field_details', { 'id': fields.Integer(readonly=True, description='The unique identifier'), 'procedure_type_id': fields.String(required=True, description='Procedure type Id'), 'name': fields.String(required=True, description='name'), 'label': fields.String(required=True, description='label'), 'type': fields.String(required=True, description='Input type'), 'default_value': fields.String(required=True, description='Default value'), 'validations': fields.String(required=True, description='validations'), })
I want to return everything in a single json that I can organize to my liking as for example
{ "procedure_name": "NAME PROCEDURE TYPE", "description": "DESCRIPTION PROCEDURE TYPE", "fields":[{ "type": "text", "name": "name_field", "id": 2, "validations": "{'required':true}", "default_value": "", "label": "LABEL 2", "procedure_type_id": "1" }, { "type": "text", "name": "name_field", "id": 2, "validations": "{'required':true}", "default_value": "", "label": "LABEL 2", "procedure_type_id": "1" } ] }
Thanks for your help
- Get response from Flask-RESTPlus in csv
I have created and REST API using Flask-RESTPlus. I am getting response in json and its fine. Now I have a new requirement to specify Response content type as csv or json.
I checked API doc there is nothing mentioned !!
Is it possible to get reponse in csv using Flask-RESTPlus ??
- flask restplus works in my local docker images but doesn't in azure
i did my flask application using flask restplus, i try it locally using runserver.py and i can see my swagger api, i put it on a docker container exposing port 80 and i run it with -p 4000:80 and also works fine, but when i send the image to the container registry in azure, and put it on my webaplication all the other end points works, but just the root that points to the swagger api page doesnt =( i get the message
No spec provided.
is there some other things that i need to expose? like another port? or might be an azure security? maybe flask restplus needs to get something from internet? like a CND website to get the colors or svgs?
thanks guys. | http://quabr.com/48248771/design-patterns-for-flask-api-implementation | CC-MAIN-2018-39 | refinedweb | 2,214 | 59.5 |
This preview shows
pages
1–2. Sign up
to
view the full content.
View Full
Document
This
preview
has intentionally blurred sections.
Unformatted text preview: 1 1 Recursion : If you get the point, stop; otherwise, see Recursion. Infinite recursion : See Infinite recursion. Read: pp. 403-408 but SKIP sect. 15.1.2 ProgramLive CD, page 15-3, has interesting recursive methods. Download presented algorithms from the website Recursive defnition : A defnition that is defned in terms oF itselF. Recursive method : a method that calls itselF (directly or indirectly). Recursion is oFten a good alternative to iteration (loops), which we cover later. Recursion is an important programming tool. Purely Functional languages have no loops only recursion. CS1110 30 September. Recursion Prelim I 7:309:00PM Thursday, 7 Oct /** = the number oF es in s */ public String noe(String s) { iF (s.length() == 0) { return 0; } // { s has at least one char } } 2 Called the base case Called the recursive case Express the answer with the same terminology as the specifcation, but on a smaller scale: number oF es in s = (iF s[0] = e then 1 else 0) + number oF es in s[1..] return (s[0] = e ? 1 : 0) + noe(s.substring(1)); Notation: s[i] shorthand For s.charAt[i]. s[i..] shorthand For s.substring(i). s 0 1 s.length() 3 Two issues in coming to grips with recursion 1. How are recursive calls executed? 2. How do we understand a recursive method and how do we create one? We discussed the frst issue earlier. IF you execute a call on a recursive method careFully, using our model oF execution, you will see that it works. Briey, a new Frame is created For each recursive call. We do this in the next lecture. DONT try to understand a recursive method by executing its recursive calls! Use execution only to understand how it works....
View Full Document
This note was uploaded on 11/27/2010 for the course CS 9339 at Cornell University (Engineering School).
- '09
- GRIES
Click to edit the document details | https://www.coursehero.com/file/6031019/Lecture-10-Recursion/ | CC-MAIN-2017-09 | refinedweb | 345 | 69.38 |
We won't lie to you?the fx.movie.edu example we showed you was unrealistic for several reasons. The main one is the magical appearance of the special-effects lab's hosts. In the real world, the lab would have started out with a few hosts, probably in the movie.edu zone. After a generous endowment, an NSF grant, or a corporate gift, they might expand the lab a little and buy a few more computers. Sooner or later, the lab would have enough hosts to warrant the creation of a new subdomain. By that point, however, many of the original hosts would be well known by their names under movie.edu.
We the DNS console, you can create CNAMEs for hosts. This allows users to continue using the old domain names for any of the hosts that have moved. When they telnet or ftp (or whatever) to those hosts, however, the command will report that they're connected to a host in fx.movie.edu:
C:\>.
How do you create all these aliases? Well, you could do it manually using the DNS console, CNAME record by CNAME record. Or you could use a Perl script to create CNAME records for every host in fx.movie.edu.dns:
# # Simple Perl script to create aliases # Run with <script> <domain name of child zone> # die "Usage: $0 <child zone>\n" if $#ARGV!=0; open(ZDF, "$ARGV[0].dns") || die "Couldn't open $ARGV[0]: $!\n"; ($label, $parent) = split(/\./, $ARGV[0], 2); $parent .= ".dns"; open(PZDF, ">>$parent") || die "Couldn't open $parent: $!\n"; while (<ZDF>) { if (/\s+IN\s+A\s+/) { ($host, $rest) = split(/[\s\.]/, $_, 2); printf PZDF "%s IN CNAME %s.%s.\n", $host, $host, $ARGV[0]; } };
Although parent-level aliases are useful for minimizing the impact of moving your hosts, they're also a crutch of sorts. Like a crutch, they'll restrict your freedom. They'll clutter up your parent namespace when one of your motivations for implementing a subdomain may have been making the parent zone smaller. And they'll prevent you from using the names of hosts in the subdomain as names for hosts in the parent zone.
After a grace period?which should be well advertised to users?you should remove all the aliases, with the possible exception of aliases for extremely well-known Internet hosts. During the grace period, users can adjust to the new domain names and modify scripts and the like. But don't get suckered into leaving all those aliases in the parent zone; they defeat part of the purpose of DNS because at the parent zone level. | http://etutorials.org/Server+Administration/dns+windows+server/Chapter+10.+Parenting/10.7+Managing+the+Transition+to+Subdomains/ | CC-MAIN-2018-30 | refinedweb | 437 | 75 |
Ok, this may be a bit difficult to explain for me, but i'll try my best.
We (and by 'we' I mean 'my higher ups') want to phone a specific number trough our app. That is the easy part.
The problem is that, when the button is pushed, prompts you to the telephone editor screen, were you can delete digits, make the call or cancel.
We (refer to the previous parentheses) don't want that. We need to, when the user presses the aforementioned button, call that number directly.
With no intermediate steps.
If this is not possible, please give us a thorough explanation. I'm a bit in a pickle here.
Kind regards
@RicardoS, this is making the call directly for me:
public async Task<Boolean> Dialer(String number) { Boolean success = false; context = MainApplication.CurrentContext; if (context == null) return success; intent = new Intent(Intent.ActionCall); intent.SetData(Uri.Parse("tel:" + number)); Boolean intentAvailable = IsIntentAvailable(); if (intentAvailable) success = context.StartActivity(intent); return success; }
@RicardoS said:
() { }
public void MakePhoneCall (string number, string name = null) { if (string.IsNullOrWhiteSpace (number)) { throw new ArgumentException ("number"); } Intent dialIntent = new Intent (Intent.ActionCall, CreateNSUri (number)); Forms.Context.StartActivity (dialIntent); } private Uri CreateNSUri (string phoneNumber) { return Uri.Parse ($"tel:{phoneNumber}"); } }
}.
Answers
That isn't possible, can you imagine the number of apps with a hidden rogue dialler calling premium rate numbers if it was possible?
@JohnHair Thank you for your response.
I hope this quench my higher ups thirst for solutions.
I don't know if this helps or if this is what you're already doing but...
stackoverflow.com/questions/37551576/how-to-make-a-phone-call-in-xamarin-forms-by-clicking-on-a-label
Ricardo was asking specifically how to not display the dialler.
@bifedefrango Yeah, what JohnHair said.
I tried that one before.
@JohnHair If anything we'll go back to the "show the dialer".
I think that @JohnHair is right then, when he said "That isn't possible, can you imagine the number of apps with a hidden rogue dialler calling premium rate numbers if it was possible?" ...
And anyway I think you should reconsider because the user may press the "call" button by accident and he's not given the choise if he really wants to do it...
@bifedefrango I know.
The problem is that I have to search for it thoroughly so that the higher ups understand that it cannot be done.
@RicardoS, this is making the call directly for me:
Thank you, @deczaloth .
I'll try later.
Tell the higher ups it's a dumbass idea and if this is a consumer app, people will soon uninstall it.....Yeah, I know you can't say that
@deczaloth What is this for?
Android?
iOS?
Forms?
No, @NMackay . It's not a consumer app. It's, ehh... for another company?
That's all I can tell.
But I'll keep those words in mind
It's Xamarin Android code, should be easy enough to spot that.
() { }
}
Ooops, i forgot the forms interface:
namespace Conductores {
public interface IPhoneCallTask {
void MakePhoneCall (string number, string name = null);
}
}.
This link might help, I really would test this on hardware and check how specific OS version cope.
Thank you @NMackay
Well, i am not sure about iOS, but in android it IS possible, as you can yourself see if you try the code i shared above (at least that is working on my side testing with a Samsung S7).
I beg your pardon, but i do not understand that. How could an App make calls to "premium rate numbers" without you knowing, and even if an app would do that (i still do not see the point) you can always hang up... or am i missing something?
@NMackay, why exactly is that a "dumbass idea"? I am using the code i shared above in my own App (my users can store contacts information and call them by tapping a button), and ...well, i would like to know why do you think it is such a bad practice...
The original poster was asking to make a call without the dialler, what if the button says something like 'Play Game' and calls a premium rate number? The user wouldn't know.
So it does display a dialer? It must do to be able to cancel the call.
It does launch the Android phone app, but you can not edit the number since the call is automatically made. You can hang up, thou.
I think the point was that @RicardoS wanted not to let the user editing the number to call:
As you point out they can cancel the call, he did mention he didn't want to delete digits, make the call or cancel.
I get your point :P
I assumed the app was going to dial without the user been aware or not been obvious. Dumbass was a tad strong but was meant in jest and yes, if your re-inventing WhatsApp etc then all good, there are API's to the dialler. As an end user I just always like to be presented with the control (Pop native dialler or default email client etc) but I retract the dumbass bit, it just wasn't obvious from the original post. No harm done.
@RicardoS @deczaloth @JohnHair @NMackay My 2 cents here:
I started my mobile development in 2010 with Windows Phone. iPhone was already established then and Android was just picking up.
Yes, at that time all 3 platforms allowed to call direct dialing API from an app. Soon after they got complaints and all 3 platforms started blocking access to direct call APIs and forced route through the built-in dialer app.
Ever since I was hearing the demands / requests / opinions for direct dialing access...nothing happened and no platform budged.
WhatsApp and Facebook appears to be allowing direct dialing, but that is within their system. They don't call landlines or cellphones.
I am aware of availability of dialing services for a fee. If someone doesn't want to hit the phone's call button once again, then they may avail those services at cost.
Yeah, I should add I've only seen the phone API in Android used for monitoring inbound calls etc, the approach posted a link to earlier seems to be the only way.
The original post was open to interpretation. My reading of it is that the important bit is that call should be made "With no intermediate steps", with the mention of cancellation being a "problem" referring to cancelling before the call is initiated, not terminating a call in progress. @RicardoS - can you confirm that is what you meant please.
The code posted by @deczaloth above does work - initiating a call without the intermediate step. On recent versions of Android the user does explicitly need to grant permission to the app for this to happen (I currently use James Montemagno's plugin for this), so on those Android versions the app cannot start making calls without the user having granted permission for it to do so. The user can subsequently revoke permission if so desired.
I am undecided regarding whether this is a good idea or not. The app that I am working on can make calls. I am still looking at the use cases before making a final decision about whether or not to include the intermediate dialler step. I might even switch depending on the Android version, so that the versions requiring permission to be granted can skip the dialler step, but versions that don't require permission do show the dialler. Options, options...
Also worth noting that calling in Android has different permission levels, on later versions it falls under "protected/dangerous permissions" and you explicitly have to request permission regardless of manifest (having had to implement this).
Exactly - the user has to explicitly grant the permission at run-time, so apps cannot run amok on those later Android versions. If the user does grant that permission, the user can revoke it again.
Guys, please calm down.
It's not that urgent nor important.
Just a secondary feature.
Our app does not depend on this.
I almost made a haiku
Ok, everything works as expected.
Thank you to all for the help and this awesome time.
Seriously though, this whole thread was a riot.
| https://forums.xamarin.com/discussion/comment/364706/ | CC-MAIN-2019-30 | refinedweb | 1,387 | 64.51 |
in reply to Handling cascading defaults
Well, I disagree strongly that you should avoid OO just because the code
is small. Just yesterday I wrote an OO module that was under 20 lines.
At this point, since you've not shown the need for inheritance
implementation reuse or even interface reuse, I'd stay away from the
complexity of objects. My personal rule is not to pull in OO technology
in Perl until the line count of the program exceeds about 1000 lines, and
using all the OO features of abstraction, inheritance, and data hiding
all becomes useful.
Well, I find that implementation reuse and inheritance are way over
emphasized in OO and almost never happen (outside of standard
libraries that get shipped with the language). Although I see a small
percentage of objects that do interface reuse (via inheritance), the
majority don't do any of those things.
In Perl the most common big advantages I see from OO are reduction of
namespace collisions and simplified compartmentalization of configuration
settings (my other favorite is cleaning up via destructors, but not all objects involve such). Here we want cascading defaults (ie. compartmentalization
of configuration settings), which is done very nicely and naturely in
Perl OO (I've never noticed it being done nicely in Perl in the absense
of OO). I find that using Perl OO almost gives you cascading defaults
without even trying.
Have a package global that contains the default configuration parameters.
Have a constructor that copies the configuration parameters from the
package or object that was used to call it. Provide methods for changing
configuration parameters (but only on constructed objects, not on the
package global of sane defaults). (Heck, if writing methods seems like
too much work, you can let the module user directly set the parameters
using $obj->{param_name} -- though I think you'd be wrong
both in thinking that writing methods is too much work and in encouraging
such unverified manipulation of your object's members.)
If you want script-level defaults, then you can also make this easy by
making it easy to export/import a default error object for the script
(see below).
Also, a package that starts out at 20 lines could eventually grow to over
1000. Retrofitting OO at that point would be a huge pain. I wouldn't
necessarilly start all projects as OO modules. But once you get to the
point that you see a need to use the code from multiple scripts and that
therefore it makes sense to turn it into a module, then I think it also
usually (in Perl) makes sense to put in OO.
package Err;
use base qw( Exporter );
use Carp qw( croak );
my( %defaults, @options );
BEGIN {
%defaults= (
Title => 'An error has occurred',
Message => 'If error persists, seek assistance',
);
@options= keys(%defaults);
}
sub new {
my $this= shift; # Either a package name or an object.
croak 'Usage: $handle= ',__PACKAGE__,"->new();\n",
' or: $handle= $ErrHandle->new()',"\n"
if @ARGV;
my $class= ref($this) || $this;
# Copy defaults from calling object or use standard defaults:
my $obj= ref($this) ? {%$this} : {%defaults};
return bless $obj, $class;
}
sub import {
# Export a unique $ErrHandle to each caller:
my $uniq= $_[0]->new();
*ErrHandle= \$uniq;
goto &Exporter::import;
}
sub Configure {
my( $self, $opts )= @_;
croak 'Usage: $ErrHandle->Configure( ',
'{ Title=>"new title", Message=>"new msg" } )', "\n"
unless 2 == @ARGV && ref($opts)
&& UNIVERSAL::isa($opts,"HASH");
my @err= grep { ! exists $defaults{$_} } keys %$opts;
croak __PACKAGE__,"::Configure: Unknown option(s) ",
"(@err) not (@options)\n"
if @err;
@{$self}{keys %$opts}= values %$opts;
return $self;
}
[download]
Now add a method that actually reports the error (you just had "do something"
in your example). And you use it like this:
use Err qw( $ErrHandle );
# Set script-specific defaults:
$ErrHandle->Configure( {Message=>"Contact technical support"} );
# Use script defaults:
$ErrHandle->Report(...);
# Set and use other configurations:
my $accountingErrHandle= $ErrHandle->new()->Configure(
{Message=>"Please notify Bob"} );
$accountingErrHandle->Report(...);
[download]
Note that you can now add a new configuration parameter by just adding
one line specifying the name and default value for it. At 40 lines, it
is more complex than what we started out with. But a lot of that has
to do with the request for script-level defaults and some nice things
I added like croak()ing when a method is called incorrectly.
In summary, I think you can write very small but reasonable OO modules
when you have something that starts out very simple but that you want to
use several places. I think that in the long run you'll be glad you
did start out with OO.
Update: Fixed unmatched quotes in my
still-thoroughly-untested sample code. Actually, I was
forced to test the exporting of a unique scalar stuff
before posting since I'd never actually done that before
(actually).).
PerlMonks, of course - how could you ask?
Other tech
Porn
Shopping
News
Sports
Games & puzzles
Social media
Arts & music
Job hunting
Whichever pays my bills
Results (207 votes). Check out past polls. | https://www.perlmonks.org/index.pl/?node_id=28669 | CC-MAIN-2020-45 | refinedweb | 831 | 57.2 |
.
OpenSSL DES APIs
Finnbarr P. Murphy
(fpm@fpmurphy.com)
Now that OpenSSL has finally reached version 1.0.0, I decided to take another look how the various Data Encryption Standard (DES) application programming interfaces (routines) included in OpenSSL can be used to encrypt and decrypt data. Since there is also a lack of simple examples available on the Internet of how to actually use the OpenSSL DES routines, I have included a
number of examples in this post to encourage readers to experiment with these routines.
The original author of the DES routines in OpenSSL s libcrypto was Eric Young. Young and Tim
Hudson posted the first version of of a free cryptographic library called SSLeay (eay stands for
Eric A, Young) to the Internet in 1995. Amazingly Young managed to single-handedly implement
the full suite of cryptosystems used in SSLeay. Since then the SSLeay library has become part of
OpenSSL. However you will still frequently come across references to SSLeay in both man pages
and the source code. Young is still involved in cryptography and currently works for RSA, the
security division of EMC.
Some background information on DES is probably in order for those who have forgotten their
college course on cryptography. DES has been around for quite a long time. It was developed by
IBM as enhancement to an existing key generator algorithm called Lucifer that was primarily
developed by Horst Feistel. It became a standard in 1977 when the National Bureau of Standards
(now called NIST) issued Federal Information Processing Standards Publication 46 (FIPS 46). That
standard specified that DES be used within the Federal Government for the cryptographic
protection of sensitive, but unclassified, computer data.
DES is a member of the class of ciphers (British English: cyphers) called a block cipher. In a block
cipher, a block of N bits from the plaintext is replaced with a block of N bits from the ciphertext.
Ideally the relationship between the input block and the output block is completely random but
invertible. This implies a one-to- one relationship with each input block being mapped to a unique
output block. Mathematically, DES maps the set of all possible 64-bit vectors onto itself. Selecting
a DES cryptographic key allows a user to select one of the possible mappings
Technically speaking, DES is an iterative, block, product cipher system (encryption algorithm). A
product cipher system mixes transposition and substitution operations in an alternating manner.
Iterations refers to the use of the output of an operation as the input for another iteration of the
same procedure. This is known as a Feistel structure or Feistel network. A cryptographic system
based on a Feistel structure uses the same basic algorithm for both encryption and decryption. A
large proportion of block ciphers, including DES, use a Festel structure.
03-03-2011
1/12
The algorithmic implementation of DES is known as Data Encryption Algorithm (DEA). DEA uses
sixteen iterations of a pair of transposition and substitution operations to encrypt or decrypt an
input block. All computations are linear except for the Substitution-boxes (S-boxes) which provide
the non-linear substitution component of the algorithm. Linear algorithms can be easily broken
using a known plaintext attack. The S-boxes in DEA effectively hinder this form of attack (Claude
Shannon s diffusion property.) The number of rounds (16) is important also. An 8-round DEA can
be broken in a few minutes on a PC using a chosen plaintext attack, i.e. differential cryptoanalysis.
When DEA was proposed, there was considerable criticism with most of it directed at the S-boxes.
It was even suggested the the S-boxes might contain a trapdoor. One useful property of DEA is
that it can be implemented very efficiently in software (or in hardware for that matter) using table
look-up. DES uses a 56-bit encryption key and a 64-bit block. The key itself is specified with 8
bytes (64-bits), but the last bit of each byte is used as a parity check of the other 7 bits. Round
keys are 48-bits and are generated from the 56-bit encryption key by a sequence of permutations.
Several methods of incorporating DES into a cryptographic system are possible. Generally speaking, these can be classified into either block or stream methods. In addition a number of modes of operation are specified by the FIPS 81 (DES Modes of Operation) standard. The modes specify how data will be encrypted and decrypted. These are summarized below.
Electronic Codebook Mode (ECB)
● 64 bits (i.e. a block) are enciphered at a time.
● The order of the blocks can be rearranged without detection.
● A plaintext block always produces the same ciphertext block for the same key.
● An error only affects one ciphertext block.
2/12
● Use discouraged as vulnerable to a directory attack
Cipher Block Chaining Mode (CBC)
●
Multiples of 64 bits are enciphered at a time.
Blocks cannot be rearranged. Each ciphertext block depends on the current and all preceding plaintext blocks.
A plaintext block always produces the same ciphertext block for the same key and starting
variable.
Different starting variables prevent the same plaintext enciphering to the same ciphertext.
An error affects the current and following ciphertext blocks.
Cipher Feedback Mode (CFB)
Only blocks of j <= 64 bits are enciphered at a time.
A small j requires more cycles through the encipherment algorithm per unit of plaintext and thus
greater processing overhead.
Blocks cannot be rearranged. Each ciphertext block depends on the current and all preceding
plaintext blocks.
Different starting variables are used to prevent the same plaintext enciphering to the same
ciphertext.
The strength of this mode depends on the size of the key k (best if j == k).
An error will affect the current and the following ciphertext blocks.
Output Feedback Mode (OFB)
Absence of chaining makes this mode vulnerable to specific attacks.
Different start variable values prevent the same plaintext enciphering to the same ciphertext, by
producing different key streams.
An error bit in the ciphertext causes only one bit to be in error in the deciphered plaintext.
It is not self-synchronizing.
Triple-DES ECB Mode
● Encrypt with key1, decrypt with key2 and encrypt with key3 again.
● As for ECB encryption but increases the key length to 168 bits.
● all keys are the same it is equivalent to encrypting once with just one key.
If
● the first and last key are the same, the key length is 112 bits.
● all 3 keys are the same, this is effectively the same as normal ECB mode.
Triple-DES CBC Mode
● Encrypt with key1, decrypt with key2 and then encrypt with key3.
● As for CBC encryption but increases the key length to 168 bits with the same restrictions as the Triple-DES ESB mode
Our first example shows how to use the basic DES encryption routine, DES_ecb_encrypt(), to
3/12
encrypt or decrypt a single 64-bit block of plaintext to electronic code book (ECB) mode. If the encrypt argument is DES_ENCRYPT, the input (plaintext) is encrypted into the output (ciphertext) using the specified key_schedule. If the encrypt argument is DES_DECRYPT, the input (ciphertext) is decrypted into the output (plaintext). Note that input and output may overlap.
#include <stdio.h> #include <string.h> #include <stdlib.h>
#include <openssl/des.h> #include <openssl/rand.h> #define BUFSIZE 64 int main(void)
{
unsigned char in[BUFSIZE], out[BUFSIZE], back[BUFSIZE];
unsigned char *e = out;
DES_cblock key;
DES_cblock seed = {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10};
DES_key_schedule keysched;
memset(in, 0, sizeof(in));
memset(out, 0, sizeof(out));
memset(back, 0, sizeof(back));
RAND_seed(seed, sizeof(DES_cblock));
DES_random_key(&key);
DES_set_key((C_Block *)key, &keysched);
/* 8 bytes of plaintext */
strcpy(in, "HillTown");
printf("Plaintext: [%s]\n", in);
DES_ecb_encrypt((C_Block *)in,(C_Block *)out, &keysched, DES_ENCRYPT);
printf("Ciphertext:");
while (*e) printf(" [%02x]", *e++);
printf("\n");
DES_ecb_encrypt((C_Block *)out,(C_Block *)back, &keysched, DES_DECRYPT);
printf("Decrypted Text: [%s]\n", back);
return(0);
}
Note the use of C_Block. The examples in this post use C_Block because that is what I am used to
using. If you are writting new code for modern platforms, you should use DES_cblock rather than
C_Block or des_cblock. See des.h for the defintion of DES_cblock, i.e. typedef unsigned char
DES_cblock[8].
Here the output when the program is compiled and executed.
$ gcc -o example1 example1.c -lcrypto
$ ./example1
Plaintext: [HillTown]
Ciphertext: [34] [bc] [85] [30] [14] [95] [43] [00]
Decrypted Text: [HillTown]
$
Examining the above code you will see that there are two parts to using DES encryption. The first is the generation of a DES_key_schedule from a key, the second is the actual encryption or decryption. A DES key is of type DES_cblock which consists of 8 bytes with odd parity. The least significant bit in each byte is the parity bit. The key schedule is an expanded platform-dependent form of the key which is used to speed the encryption process. The example uses a seeded PRNG ( RAND_seed()) to generate a random 64-bit DES key. Notice that I explicitly zero all storage that the example uses; always a good idea when using OpenSSL library routines. Examining the output, you will see that the size of the ciphertext is the same as the plaintext. This is a characteristic of a
4/12
block cipher. Note that if you compile and run this example, you will not get the same ciphertext as I got due to the fact that the example uses a randomly generated key.
Our next example demonstrates the Triple-DES mode. For some reason a lot of people are unaware that FIPS-46 actually specifies two modes for Triple-DES:
● EDE (Encrypt-Decrypt-Encrypt) where ciphertext = Ek3(Dk2(Ek1(plaintext)))
● EEE (Encrypt-Encrypt-Encrypt) where ciphertext = Ek3(Ek2(Ek1(pliantext)))
where Ek and Dk denote DES encryption and decryption respectively. In addition, ANSI X9.52 defines three key options for Triple-DES:
● k1 != k2 != k3
● k1 != k2, k1 = k3, k2 != k3
● k1 = k2 = k3
The third option makes Triple-DES backwardly compatible with DES. The recommended usage
mode, per FIPS-46, for Triple-DES is EEE or EDE with three independently generated keys, i.e.
168 key bits in total. OpenSSL uses the EDE mode.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <openssl/des.h>
#include <openssl/rand.h>
#define BUFSIZE 1024
int main(void)
int i;
DES_cblock key1, key2, key3;
DES_key_schedule ks1, ks2, ks3;
DES_random_key(&key1);
DES_random_key(&key2);
DES_random_key(&key3);
DES_set_key((C_Block *)key1, &ks1);
DES_set_key((C_Block *)key2, &ks2);
DES_set_key((C_Block *)key3, &ks3);
/* 64 bytes of plaintext */
strcpy(in, "Now is the time for all men to stand up and be counted");
for (i = 0; i < 63; i += 8) {
DES_ecb3_encrypt((C_Block *)(in + i),(C_Block *)(out + i), &ks1, &ks2, &am p;ks3, DES_ENCRYPT);
printf("Ciphertext:"); while (e++) printf(" [%02x]", *e++);
printf("\n"); for (i = 0; i < 63; i += 8) { DES_ecb3_encrypt((C_Block *)(out + i),(C_Block *)(back + i), &ks1, &ks2, & amp;ks3, DES_DECRYPT);
exit(0);
5/12
As you can see, this example uses three different keys (k1 != k2 != k3) which is the recommended way of using Triple-DES. Here is the output when this example is compiled and executed:
[fpm@ultra ~]$ ./example2 Plaintext: [Now is the time for all men to stand up and be counted]
Ciphertext: [b4] [31] [40] [aa] [41] [7d] [fc] [72] [4b] [f7] [46] [b5] [24] [83] [95] [03
]
[38] [1a] [50] [4e] [65] [5e] [83] [19] [b4] [0f] [74] [8b] [0c] [de] [5f] [34] [bf] [ee
[65] [4a] [b1] [0d] [33] [b4] [db] [cd] [02] [2c] [6c] [39] [7e] [57] [0d] [99] [18] [69
] [23] [56] [fb] [00] Decrypted Text: [Now is the time for all men to stand up and be counted] [fpm@ultra ~]$
The next example demonstrates the Cipher Block Chaining mode. In this mode each block is
XOR-ed with the previous cipherblock before encryption.
Because changes in the plaintext propagate forever in the ciphertext, encryption cannot be
parallelized. For the first block we start with an initiallization vector (ivec). Note that it is not
unusual to start with a zero vector as the initialization vector. Note that there is both a
DES_cbc_encrypt() and a DES_ncbc_encrypt() in libcrypto. I recommend you only use the ncbc
version (n stands for new). See the BUGS section of the OpenSSL DES manpage and the source
code for these functions.
#define BUFSIZE 512
int len;
DES_cblock ivsetup = {0xE1, 0xE2, 0xE3, 0xD4, 0xD5, 0xC6, 0xC7, 0xA8};
DES_cblock ivec;
DES_set_odd_parity(&key);
if (DES_set_key_checked((C_Block *)key, &keysched))
fprintf(stderr, "ERROR: Unable to set key schedule\n");
exit(1);
/* 64 bytes of plaintext */ strcpy(in, "Now is the time for all men to stand up and be counted"); printf("Plaintext: [%s]\n", in); len = strlen(in); memcpy(ivec, ivsetup, sizeof(ivsetup)); DES_ncbc_encrypt(in, out, len, &keysched, &ivec, DES_ENCRYPT); printf("Ciphertext:"); while (*e) printf(" [%02x]", *e++); printf("\n"); memcpy(ivec, ivsetup, sizeof(ivsetup)); DES_ncbc_encrypt(out, back, len, &keysched, &ivec, DES_DECRYPT);
6/12
Note that I reinitialize ivec before decrypting the ciphertext. If you do not reinitialize ivec your decrypted text will be incorrect.
The next example uses DES_ede3_ncbc_encrypt() to implement outer triple CBC DES encryption with three keys. This means that each DES operation inside the CBC mode is C=E(ks3,D(ks2,E(ks1,M))). This is the mode is used by SSL.
len = strlen(in);
memcpy(ivec, ivsetup, sizeof(ivsetup));
DES_ede3_cbc_encrypt(in, out, len, &ks1, &ks2, &ks3, &ivec, DES_ENCRYP
T);
len = strlen(out);
memcpy(ivec, ivsetup, sizeof(ivsetup)); DES_ede3_cbc_encrypt(out, back, len, &ks1, &ks2, &ks3, &ivec, DES_DECR YPT); printf("Decrypted Text: [%s]\n", back);
Note the need to reinitialize ivec before decrypting the ciphertext. If you do not do this, the first 64 bits of the resultant plaintext will be incorrect.
The next example shows the use of a modified form of the CBC mode called Triple DES Cipher Block Chaining with Output Feedback Masking. This mode provides stronger protection against dictionary attacks and matching ciphertext attacks that exploit the DES blocksize of 64 bits
7/12
through the introduction of secret masking values that are XOR-ed with the intermediate outputs of each triple-DES encryption operation. Apparantly, however, Eli Biham and Lars Knudsen have developed an attack on this mode but it requires a lot of work.
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <openssl/des.h> #include <openssl/rand.h> #define BUFSIZE 512 #define CBCM_ONE int main(void)
DES_cblock ivecstr = {0xE1, 0xE2, 0xE3, 0xD4, 0xD5, 0xC6, 0xC7, 0xA8};
DES_cblock ivec2, ivec1;
memcpy(ivec2, ivecstr, sizeof(ivecstr));
memset(ivec1,'\0',sizeof(ivec2));
len = strlen(in) + 1;
#ifdef CBCM_ONE
DES_ede3_cbcm_encrypt(in, out, len, &ks1, &ks2, &ks3, &ivec2, &ive
c1, DES_ENCRYPT);
#else
DES_ede3_cbcm_encrypt(in, out, 16, &ks1, &ks2, &ks3, &ivec2, &ivec
1, DES_ENCRYPT);
DES_ede3_cbcm_encrypt(&in[16], &out[16],len-16, &ks1, &ks2, &ks3,
&ivec2, &ivec1, DES_ENCRYPT);
#endif
while (*e) printf(" [%02x]", *e+);
len = strlen(out) + 1;
DES_ede3_cbcm_encrypt(out, back, len, &ks1, &ks2, &ks3, &ivec2, &i vec1, DES_DECRYPT); printf("Decrypted Text: [%s]\n", back);
The above example showns you two variations for encrypting the plaintext and vice-versa. The two-step approach is useful in some situations.
The next example shows the use of the Cipher Feedback (CFB) mode. CFB is a close relative of CBC but is a self-synchronizing stream cipher if the 1-bit mode is selected.
8/12
#include <stdio.h> #include <string.h> #include <stdlib.h> #include <openssl/des.h>
#include <openssl/rand.h> #define BUFSIZE 256 #define CFBMODE 1 int main(void)
unsigned char in[BUFSIZE], out[BUFSIZE], back[BUFSIZE]; unsigned char *e = out; int len; DES_cblock key;
DES_key_schedule ks;
DES_set_key((C_Block *)key, &ks);
/* 11 bytes of plaintext */
strcpy(in, "Philippines");
memcpy(ivec, ivecstr, sizeof(ivecstr));
DES_cfb_encrypt(in, out, CFBMODE, len, &ks, &ivec, DES_ENCRYPT);
DES_cfb_encrypt(out, back, CFBMODE, len, &ks, &ivec, DES_DECRYPT);
Here is an example which uses the CBF64 mode and also, for the first time, uses ASCII strings for
the initialization vector and DES key.
#define BUFSIZE 256
unsigned char in[BUFSIZE], out[BUFSIZE], back[BUFSIZE]; unsigned char *e = out; int len; int n = 0; static char *keystr = "0123456789abcdef"; static char *ivecstr = "0123456789abcdef"; DES_cblock ivec; DES_key_schedule ks; memset(in, 0, sizeof(in)); memset(out, 0, sizeof(out)); memset(back, 0, sizeof(back)); strcpy(in,"Now is the time for all."); DES_set_key((C_Block *)keystr, &ks); printf("Plaintext: [%s]\n", in);
9/12
memcpy(ivec, (C_Block *)ivecstr, sizeof(ivec)); len = strlen(in) + 1; DES_cfb64_encrypt(in, out, len, &ks, &ivec, &n, DES_ENCRYPT); printf("Ciphertext:"); while (*e) printf(" [%02x]", *e++); printf("\n"); memcpy(ivec, (C_Block *)ivecstr, sizeof(ivec)); DES_cfb64_encrypt(out, back, len, &ks, &ivec, &n, DES_DECRYPT); printf("Decrypted Text: [%s]\n", back);
Note the use of DES_string_to_key() to convert a string into a key. The inputted string should be at
least 16 characters in length.DES_string_to_key() sets odd parity so there is no need to invoke
DES_set_odd_parity().
The next example demonstrates the use of 8-bit OFB mode. This mode is an additive stream cipher
in which errors in the ciphertext are not extended to cause additional errors in the decrypted
plaintext. Thus a single bit in error in the ciphertext causes only one bit to be in error in the
decrypted plaintext. According to the OpenSSL man page, this mode should only be used for small
sizes of plaintext. From experimenting with numbits and the BUGS section of the DES manpage, I
suggest you always use a value of 8 for numbits.
char *keystr = "Philippines06235";
int len, n, result;
DES_string_to_key(keystr, &key);
if ((result = DES_set_key_checked((C_Block *)key, &ks)) != 0) {
if (result == -1) {
printf("ERROR: key parity is incorrect\n");
} else {
printf("ERROR: weak or semi-weak key\n");
strcpy(in,"The Chocolate Hills of Bohol are wonderful.");
printf("Plaintext: [%s]\n", in); memcpy(ivec, ivecstr, sizeof(ivecstr)); len = strlen(in); printf("Plaintext Length: %d\n", len); DES_ofb_encrypt(in, out, 8, len, &ks, &ivec); n = 0; printf("Ciphertext:"); while (*e) { printf(" [%02x]", *e++); n++;
10/12
printf("\n"); printf("Ciphertext Length: %d\n", n); len = strlen(out); memcpy(ivec, ivecstr, sizeof(ivecstr)); DES_ofb_encrypt(out, back, 8, len, &ks, &ivec); printf("Decrypted Text: [%s]\n", back);
The final example in this post uses ede3_ofb64_encrypt() to perform the encryption and decryption.
It also reads in the plaintext from an external file. To simplify things and shorten the example, I set k1 = k2 = k3. I will leave it up to you to modify the example to support the case where k1 !=
k2 != k3.
int main(int argc, char *argv[])
char buf[201];
char *keystr = "Victoria Harbour";
FILE *fin;
int i, num, len, result;
int n = 0;
if (argc != 2) {
printf("ERROR: plaintext filename required\n");
fin = fopen(argv[1], "r");
if (!fin) { printf(" ERROR: opening input file\n");
while(fgets(buf, 200, fin) != NULL) {
strcat(in, buf);
fclose(fin); printf("Plaintext: [%s]\n", in); len = strlen(in); printf("Plaintext Length: %d\n", len); memcpy(ivec, ivsetup, sizeof(ivsetup)); num = 0; for (i = 0; i < len; i++) { DES_ede3_ofb64_encrypt(&(in[i]), &(out[i]), 1, &ks, &ks, &ks,
11/12
&ivec, &num);
n = 0; printf("Ciphertext:"); while (*e) { printf(" [%02x]", *e++); n++;
printf("\n"); printf("Ciphertext Length: %d\n", n); memcpy(ivec, ivsetup, sizeof(ivsetup)); num = 0; for (i = 0; i < len; i++) {
DES_ede3_ofb64_encrypt(&(out[i]), &(back[i]), 1, &ks, &ks, &ks,
Here is sample output:
$ echo -n "Now is the time to finish this post" > plaintext
$ ./example9 plaintext
Plaintext: [Now is the time to finish this post]
Plaintext Length: 35
Ciphertext: [92] [cb] [29] [fe] [aa] [94] [d7] [ba] [07] [a5] [8f] [78] [4f] [13] [fa] [c4
[4f] [22] [0d] [fd] [b7] [33] [81] [3e] [3a] [e4] [f5] [c6] [52] [c9] [2b] [4f] [d5] [b8
[00]
Ciphertext Length: 35
Decrypted Text: [Now is the time to finish this post]
Well, I think I have covered the OpenSSL v1.0 DES routines in sufficient detail for most readers.
There are a number of other routines but these are infrequently used or are slight variations on
the routines used in the above examples. You may come across many references to DES routines
which start with des
These are essentially the same as the DES_ routines but are from older
versions of libcrypto. The move to DES_ occurred several years ago. You should always use the
DES_ version of a routine if it is available.
Armed with your new knowledge, you should now be able to go away and use DES within your
applications. Feel free to use any source code included in this post. If you want to learn more
about DES, Douglas Stinson does an excellent job in Chapter 3 of his book Crytography Theory
and Practice (ISBN 0-8493-8521-0). Another excellent book, with lots of C source code, is Bruce
Schneir s Applied Cryptography (ISBN 0-471-59756-2). Unfortunately, currently the OpenSSL man
pages are poor at best and downright inaccurate at worst so you may frequently find yourself
examining the libcrypto source code. All of the relevant DES code is in the subdirectory.
/crypto/des
Enjoy!
12. | https://ru.scribd.com/document/49901807/OpenSSL-DES-API | CC-MAIN-2020-45 | refinedweb | 3,484 | 61.56 |
PCRE - Perl-compatible regular expressions.
Description
Author
#include <pcre are
NULL for the "i"th argument, or pass fewer arguments than
number of sub-patterns, "i"th captured sub-pattern is
ignored., the following modifiers are supported:
modifier description Perl corresponding
PCRE_CASELESS case insensitive match /i
PCRE_MULTILINE multiple lines match /m
PCRE_DOTALL dot matches newlines /s
PCRE_DOLLAR_ENDONLY $ matches only at end N/A
PCRE_EXTRA strict escape parsing N/A
PCRE_EXTENDED ignore whitespaces /x
PCRE_UTF8 handles UTF8 chars built-in
PCRE_UNGREEDY reverses * and *? N/A
PCRE_NO_AUTO_CAPTURE disables capturing parens N/A (*)
(*) Both Perl and PCRE allow non capturing parentheses by means of the "?:" modifier within the pattern itself. e.g. (?:ab|cd) does not capture, while (ab|cd) does.
For a full account on how each modifier works, please check the PCRE API reference page.
For each modifier, there are two member functions whose name is made out of the modifier in lowercase, without the "PCRE_" prefix. For instance, PCRE_CASELESS is handled by
bool caseless()
which returns true if the modifier is set, and
RE_Options & set_caseless(bool)
which sets or unsets the modifier. Moreover, PCRE_EXTRA_MATCH_LIMIT can be accessed through the set_match_limit() and match_limit() member functions. Setting match_limit to a non-zero value will limit the execution of pcre to keep it from doing bad things like blowing the stack or taking an eternity to return a result. A value of 5000 is good enough to stop stack blowup in a 2MB thread stack. Setting match_limit to zero disables match limiting..
Normally, to pass one or more modifiers to a RE class, you declare a RE_Options object, set the appropriate options, and pass this object to a RE constructor. Example:
RE_options opt; modifier already set: CASELESS(), UTF8(), MULTILINE(), DOTALL(), and EXTENDED().
If you need to set several options at once, and you dont want to go through the pains of declaring a RE_Options object and setting several options, there is a parallel method that give you such ability on the fly. You can concatenate several set_xxxxx() member functions, since each of them returns a reference to its class object. For example, to pass PCRE_CASELESS, PCRE_EXTENDED, and PCRE_MULTILINE to a RE with one statement, you may write:
RE(" ^.
The C++ wrapper was contributed by Google Inc. | http://manpages.sgvulcan.com/pcrecpp.3.php | CC-MAIN-2017-09 | refinedweb | 373 | 52.39 |
After implementing our Twitter-clone, Ribbit, in plain PHP and Rails, it's time to introduce the next walk-through: Python! In this tutorial, we'll rebuild Ribbit using Django. Without further delay, let's get started!
Step 0 - Bootstrapping
As of the time of this writing, Django 1.4 supports Python 2.5 to 2.7.3. Before proceeding, make sure that you have the apt version by executing
python -v in the terminal. Note that Python 2.7.3 is preferred. All throughout this tutorial, we'll use pip as our package manager and virtualenv to set up the Virtual Environments. To install these, fire up the terminal and execute the following commands as root
curl | sudo python curl | sudo python sudo pip install virtualenv
To set up our Django development evironment, we'll start off by creating a Virtual Environment. Execute the following commands in the terminal (preferrably inside your development directory)
virtualenv --no-site-packages ribbit_env source ribbit_env/bin/activate
With our Virtual Environment, set up and activated (your command prompt should be changed to reflect the environmen's name), let's move on to installing the dependencies for the project. Apart from Django, we'll be using South to handle the database migrations. We'll use
pip to install both of them by executing. Do note that from here on, we'll be doing everything inside the virtualenv. As such, ensure that it's activated before proceeding.
pip install Django South
With all of the dependencies set up, we're ready to move on to creating a new Django Project.
Step 1 - Creating the Project and the Ribbit App
We'll begin by creating a new Django project and our app.
cd into your preferred directory and run:
django-admin.py startproject ribbit cd ribbit django-admin.py startapp ribbit_app
Next, we'll initialize our git repository and create a
.gitignore file inside the Ribbit project that we just created. To do so, run:
git init echo "*.pyc" >> .gitignore git add . git commit -m 'Initial Commit'
Let's move on to editing
ribbit/settings.py and configure our project. First, we'll define some constants. Add the following to the top of the file:
import os PROJECT_PATH = os.path.dirname(os.path.abspath(__file__)) LOGIN_URL = '/'
PROJECT_PATH will store the location of the directory in which settings.py is stored. This will allow us to use relative paths for future constants.
LOGIN_URL, as the name suggests, designates that the root of our site will be the URL to Login.
Moving on, let's configure the database. For the development evironment, sqlite3 is an ideal choice. To do so, edit the
DATABASES constant with the following values:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': os.path.join(PROJECT_PATH, 'database. } }
Django finds the static files from the directory mentioned in the
STATIC_ROOT constant and routes requests to the files to the path specified in
STATIC_URL. Configure them so that they reflect the following:
# Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = os.path.join(PROJECT_PATH, 'static') # URL prefix for static files. # Example: "" STATIC_URL = '/static/'
Do note the use of
os.path.join(). The function allows us to relatively specify the path using the
PROJECT_PATH constant we defined before.
Next, we need to specify the location that Django needs to look to find the template files. We'll edit the
TEMPLATE_DIRS constant to specify the path.
TEMPLATE_DIRS = ( # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. os.path.join(PROJECT_PATH, 'templates') )
Finally, let's add
South and
ribbit_app to the list of
INSTALLED_APPS.
INSTALLED_APPS = ( 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.sites', 'django.contrib.messages', 'django.contrib.staticfiles', 'south', 'ribbit_app', # Uncomment the next line to enable the admin: # 'django.contrib.admin', # Uncomment the next line to enable admin documentation: # 'django.contrib.admindocs', )
Next, let's create the directories we defined in the settings and create the database:
mkdir ribbit/static ribbit/templates ribbit_app/static python manage.py syncdb python manage.py schemamigration ribbit_app --initial python manage.py migrate ribbit_app
The
syncdb command will create the required tables and create the superuser account. Since we're using South for migrations, we make the initial migration for the app using the syntax
schemamigration <app_name> --initial and apply it with
python manage.py migrate ribbit_app
Let's start our development server to ensure everything is working correctly.
python manage.py runserver
If everything's fine indeed, you should be greeted with the following page when you visit
Further, the project tree should look like:
ribbit |-- manage.py |-- ribbit | |-- database.db | |-- __init__.py | |-- __init__.pyc | |-- settings.py | |-- settings.pyc | |-- static | |-- templates | |-- urls.py | |-- urls.pyc | |-- wsgi.py | `-- wsgi.pyc `-- ribbit_app |-- __init__.py |-- __init__.pyc |-- migrations | |-- 0001_initial.py | |-- 0001_initial.pyc | |-- __init__.py | `-- __init__.pyc |-- models.py |-- models.pyc |-- static |-- tests.py `-- views.py
Before moving on to the next step, let's commit our changes to the repo.
git add . git commit -m 'Created app and configured settings'
Step 2 - Base Template and Static Files
Following on from the interface tutorial, download the assets and place them within the
ribbit_app/static directory. We need to make some edits to
style.less for this tutorial. Let's begin with adding some styles for the flash.
; } }
Next, let's update the width of the input elements and add the error class for the same. Note that the code below contains only the styles that are required to be added or updated. The remaining code remains untouched.
input { width: 179px; &.error { background: #ffefef; color: #4c1717; border: 1px solid #4c1717; } }
We also need to increase the height of
#content.wrapper.panel.right.
height: 433px;
Finally, let's add a right margin to the footer images.
footer { div.wrapper { img { margin-right: 5px; } } }
Before moving on, let's commit the changes:
git add . git commit -m 'Added static files'
Next, let's create the base template, which will be inherited by all the other templates. Django uses it's own templating engine (like ERB or Jade). Define the template in
ribbit/templates/base.html with the following content:
<!DOCTYPE html> <html> <head> <link rel="stylesheet/less" href="{{ STATIC_URL }}style.less"> <script src="{{ STATIC_URL }}less.js"></script> </head> <body> <header> <div class="wrapper"> <img src="{{ STATIC_URL }}gfx/logo.png"> <span>Twitter Clone</span> {% block login %} <a href="/">Home</a> <a href="/users/">Public Profiles</a> <a href="/users/{{ username }}">My Profile</a> <a href="/ribbits">Public Ribbits</a> <form action="/logout"> <input type="submit" id="btnLogOut" value="Log Out"> </form> {% endblock %} </div> </header> <div id="content"> <div class="wrapper"> {% block flash %} {% if auth_form.non_field_errors or user_form.non_field_errors or ribbit_form.errors %} <div class="flash error"> {{ auth_form.non_field_errors }} {{ user_form.non_field_errors }} {{ ribbit_form.content.errors }} </div> {% endif %} {% if notice %} <div class="flash notice"> {{ notice }} </div> {% endif %} {% endblock %} {% block content %} {% endblock %} </div> </div> <footer> <div class="wrapper"> Ribbit - A Twitter Clone Tutorial <a href=""> <img src="{{ STATIC_URL }}gfx/logo-nettuts.png"> </a> <a href=""> <img src="" border="0" alt="Made with Django." title="Made with Django." /> </a> </div> </footer> </body> </html>
In the above markup,
{{ STATIC_URL }} prints the path for the static url defined in settings.py. Another feature is the use of blocks. All the content of the blocks is inherited to the sub-classes of the base template, and will not be overwritten unless the block is explicitly redefined in them. This provides us with some flexibility to place the navigation links at the header and replace it with the login form if the user isn't signed in. We're also using a block with an
if condition to check if any of the flash variables are not empty and render the messages appropriately.
Alright! Time to make another commit:
git add . git commit -m 'Created base template'
Step 3 - Creating the Models
One of the best things about Django is that it includes quite a few models and forms, which can be overridden to suite many purposes. For our application, we'll use the
User model and add a few properties to it by creating a
UserProfile Model. Further, to manage the ribbits, we'll create a
Ribbit Model as well. The
User model provided by Django includes fields to store the username, password, first and last names and email address (with validation) along with many others. I suggest you to have a look at the API to know about the all fields supported by default. Add the following code for models in
ribbit_app/models.py.
from django.db import models from django.contrib.auth.models import User import hashlib class Ribbit(models.Model): content = models.CharField(max_length=140) user = models.ForeignKey(User) creation_date = models.DateTimeField(auto_now=True, blank=True) class UserProfile(models.Model): user = models.OneToOneField(User) follows = models.ManyToManyField('self', related_name='followed_by', symmetrical=False) def gravatar_url(self): return "" % hashlib.md5(self.user.email).hexdigest() User.profile = property(lambda u: UserProfile.objects.get_or_create(user=u)[0])
Let's start with the
Ribbit Model. The attributes include a
CharField with maximum length of 140 characters to store the content, a
ForeignKey to the User model (so that we have a relation between the two models) and a
DateTimeField which is automatically populated with the time when the instance of the model is saved.
Moving on to the
UserProfile Model, we've a
OneToOne field that defines a One to One relation with the
User Model and a
ManyToMany field to implement the follows/followed_by relation. The
related_name parameter allows us to use the relation backwards using a name of our choice. We've also set
symmetrical to False to ensure that if User A follows B then User B doesn't automatically follow A. We've also defined a function to get the link to the gravatar image based upon the user's url and a property to get (if the UserProfile exists for the user) or create one when we use the syntax
<user_object>.profile. This allows us to fetch the properties of
UserProfile quite easily. Here's an example of how you might use the ORM to get the users that a given User follows and is followed by:
superUser = User.object.get(id=1) superUser.profile.follows.all() # Will return an iterator of UserProfile instances of all users that superUser follows superUse.profile.followed_by.all() # Will return an iterator of UserProfile instances of all users that follow superUser
Now that our models are defined, let's generate the migrations and apply them:
python manage.py schemamigration ribbit_app --auto python manage.py migrate ribbit_app
Before moving on, let's commit the changes
git add . git commit -m 'Created Models'
Step 4 - Creating Forms
Django allows us to create forms so that we can easily validate the data accepted by the user for irregularities. We'll create a custom form for the
Ribbit Model andcreate a form that inherits
UserCreationForm provided by default to manage the registration. For managing the authentication, we'll extend the
AuthenticationForm provided by default in Django. Let's create a new file
ribbit_app/forms.py and add the imports.
from django.contrib.auth.forms import AuthenticationForm, UserCreationForm from django.contrib.auth.models import User from django import forms from django.utils.html import strip_tags from ribbit_app.models import Ribbit
Let's begin with creating the registration form. We'll name it
UserCreateForm and it's code is given below:
class UserCreateForm(UserCreationForm): email = forms.EmailField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'Email'})) first_name = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'First Name'})) last_name = forms.CharField(required=True, widget=forms.widgets.TextInput(attrs={'placeholder': 'Last Name'})) username = forms.CharField(widget=forms.widgets.TextInput(attrs={'placeholder': 'Username'})) password1 = forms.CharField(widget=forms.widgets.PasswordInput(attrs={'placeholder': 'Password'})) password2 = forms.CharField(widget=forms.widgets.PasswordInput(attrs={'placeholder': 'Password Confirmation'})) def is_valid(self): form = super(UserCreateForm, self).is_valid() for f, error in self.errors.iteritems(): if f != '__all_': self.fields[f].widget.attrs.update({'class': 'error', 'value': strip_tags(error)}) return form class Meta: fields = ['email', 'username', 'first_name', 'last_name', 'password1', 'password2'] model = User
In the form above, we've explicitly set some of the fields as mandatory by passing in
required=True. Further, I've added the placeholder attribute to the different widgets used by the forms. A class named
error is also added to the fields that contain errors. This is done in the
is_valid() function. Finally, in the
Meta class, we can specify the order in which we want our form fields to render and set the model against which the form should be validated.
Next, let's write the form for the authentication:
class AuthenticateForm(AuthenticationForm): username = forms.CharField(widget=forms.widgets.TextInput(attrs={'placeholder': 'Username'})) password = forms.CharField(widget=forms.widgets.PasswordInput(attrs={'placeholder': 'Password'})) def is_valid(self): form = super(AuthenticateForm, self).is_valid() for f, error in self.errors.iteritems(): if f != '__all__': self.fields[f].widget.attrs.update({'class': 'error', 'value': strip_tags(error)}) return form
As in the
UserCreateForm, the
AuthenticateForm adds some placeholders and error classes.
Finally, let's finish up form, to accept a new Ribbit.
class RibbitForm(forms.ModelForm): content = forms.CharField(required=True, widget=forms.widgets.Textarea(attrs={'class': 'ribbitText'})) def is_valid(self): form = super(RibbitForm, self).is_valid() for f in self.errors.iterkeys(): if f != '__all__': self.fields[f].widget.attrs.update({'class': 'error ribbitText'}) return form class Meta: model = Ribbit exclude = ('user',)
The exclude option in the
Meta class above prevents the user field from being rendered. We don't need it since the Ribbit's user will be decided by using sessions.
Let's commit the changes we've made so far
git add . git commit -m 'Created Forms'
Step 5 - Implementing Sign Up and Login
Django offers great flexibility when it comes to routing. Let's begin by defining some routes in
ribbit/urls.py.
urlpatterns = patterns('', # Examples: url(r'^$', 'ribbit_app.views.index'), # root url(r'^login$', 'ribbit_app.views.login_view'), # login url(r'^logout$', 'ribbit_app.views.logout_view'), # logout url(r'^signup$', 'ribbit_app.views.signup'), # signup )
Next, let's make use of the models and forms we've just made and write the corresponding views for each route we've just defined.. Let's start by adding the imports in
ribbit_app/views.py.
from django.shortcuts import render, redirect from django.contrib.auth import login, authenticate, logout from django.contrib.auth.models import User from ribbit_app.forms import AuthenticateForm, UserCreateForm, RibbitForm from ribbit_app.models import Ribbit
Followed by the index view:
def index(request, auth_form=None, user_form=None): # User is logged in if request.user.is_authenticated(): ribbit_form = RibbitForm() user = request.user ribbits_self = Ribbit.objects.filter(user=user.id) ribbits_buddies = Ribbit.objects.filter(user__userprofile__in=user.profile.follows.all) ribbits = ribbits_self | ribbits_buddies return render(request, 'buddies.html', {'ribbit_form': ribbit_form, 'user': user, 'ribbits': ribbits, 'next_url': '/', }) else: # User is not logged in auth_form = auth_form or AuthenticateForm() user_form = user_form or UserCreateForm() return render(request, 'home.html', {'auth_form': auth_form, 'user_form': user_form, })
For the index view, we first check if the user is logged in or not and render the templates, accordingly. The querysets
ribbits_self and
ribbits_buddies are merged with the
| operator in the above code. Also, we check if an instance of a form has been passed to the method (in the function definition) and if not we create a new one. This allows us to pass around form instances to the appropriate templates and render the errors.
Let's proceed with editing the 'home.html' template which will be used to show the index page for anonymous users. In the
ribbit/templates/home.html file, add the following code.
{% extends "base.html" %} {% block login %} <form action="/login" method="post">{% csrf_token %} {% for field in auth_form %} {{ field }} {% endfor %} <input type="submit" id="btnLogIn" value="Log In"> </form> {% endblock %} {% block content %} {% if auth_form.non_field_errors or user_form.non_field_errors %} <div class="flash error"> {{ auth_form.non_field_errors }} {{ user_form.non_field_errors }} </div> {% endif %} <img src="{{ STATIC_URL}}gfx/frog.jpg"> <div class="panel right"> <h1>New to Ribbit?</h1> <p> <form action="/signup" method="post">{% csrf_token %} {% for field in user_form %} {{ field }} {% endfor %} <input type="submit" value="Create Account"> </form> </p> </div> {% endblock %}
In the template, we inherit the base template defined before, render the authentication and sign up forms by overriding the login block. A neat thing about Django is that it makes CSRF Protection quite easy! All you need to do is add a
csrf_token in every form you use in the template.
Let's move on to the
buddies.html template, which will show the Buddies' Ribbit page. Edit
ribbit/templates/buddies.html and add the following code:
{% extends "base.html" %} {% block login %} {% with user.username as username %} {{ block.super }} {% endwith %} {% endblock %} {%>Buddies' Ribbits</h1> {% for ribbit in ribbits %} <div class="ribbitWrapper"> <a href="/users/{{ ribbit.user.username }}"> <img class="avatar" src="{{ ribbit.user.profile.gravatar_url }}"> <span class="name">{{ ribbit.user.first_name }}</span> </a> @{{ ribbit.user.username }} <p> {{ ribbit.content }} </p> </div> {% endfor %} </div> {% endblock %}
In this template, we provide the parent template i.e.
base.html with the value of username so that the navigation link for the logged in User's profile renders correctly. We're also using an instance of
RibbitForm to accept new Ribbits and looping over and showing the current ribbits by our buddies.
With the templates finished, let's move on and write the code to log in/out the user. Add the following code to
ribbit_app/views.py
def login_view(request): if request.method == 'POST': form = AuthenticateForm(data=request.POST) if form.is_valid(): login(request, form.get_user()) # Success return redirect('/') else: # Failure return index(request, auth_form=form) return redirect('/') def logout_view(request): logout(request) return redirect('/')
The views for login expect a HTTP POST request for the login (since the form's method is POST). It validates the form and, if successful, logins the user using the
login() method which starts the session and then redirects to the root url. If the validation fails, we pass the instance of the
auth_form received from the user to the index function and list the errors, whereas, if the request isn't POST then the user is redirected to the root url.
The logout view is relatively simpler. It utilizes the
logout() function in Django which deletes the session and logs the user out followed by redirecting to the root url.
We now need to write the view to sign up and register a user. Append the following code to ribbit_app/views.py.
def signup(request): user_form = UserCreateForm(data=request.POST) if request.method == 'POST': if user_form.is_valid(): username = user_form.clean_username() password = user_form.clean_password2() user_form.save() user = authenticate(username=username, password=password) login(request, user) return redirect('/') else: return index(request, user_form=user_form) return redirect('/')
Similar to the login view, the signup view expects a POST request as well and redirects to the root url if the check fails. If the Sign Up form is valid, the user is saved to the database, authenticated, logged in and then redirected to the home page. Otherwise, we call the index function and pass in the instance of
user_form submitted by the user to list out the errors.
Let's check our progress by starting the server and testing the views we've written so far manually.
python manage.py runserver
Let's visit our Development Server and try registering a new user. If all goes well, you should be presented with the Buddies' Ribbits page. We can logout and reauthenticate the newly created user to check if the sign in functions work as expected.
Time to commit the changes!
git add . git commit -m 'Implemented User Login and Sign Up'
Step 6 - Accepting new Ribbits and Listing Public Ribbits
In the
buddies.html template we created before, the ribbit_form was submitted to
/submit. Let's edit
ribbit/urls.py and add the route for the form and the page to list all the public ribbits. )
Let's write a view to validate and store the ribbits submitted. Open up
ribbit_app/views.py and append the following code:
from django.contrib.auth.decorators import login_required @login_required def submit(request): if request.method == "POST": ribbit_form = RibbitForm(data=request.POST) next_url = request.POST.get("next_url", "/") if ribbit_form.is_valid(): ribbit = ribbit_form.save(commit=False) ribbit.user = request.user ribbit.save() return redirect(next_url) else: return public(request, ribbit_form) return redirect('/')
The view uses the
@login_required decorator, which executes the function only if the user is authenticated; else, the user is redirected to the path specified in
LOGIN_URL constant in the settings. If the form validation is successful, we manually set the user to the one contained in the session and then save the records. After the database commit, the user is redirected to the path specified in
next_url field which is a hidden form field we manually entered in the template for this purpose. The value of
next_url is passed along in the views that render the Ribbit Form.
Moving on, let's write the view to list the last 10 Public Ribbits. Append the following in
ribbit_app/views.py
@login_required def public(request, ribbit_form=None): ribbit_form = ribbit_form or RibbitForm() ribbits = Ribbit.objects.reverse()[:10] return render(request, 'public.html', {'ribbit_form': ribbit_form, 'next_url': '/ribbits', 'ribbits': ribbits, 'username': request.user.username})
In the public view, we query the database for the last 10 ribbits by slicing the queryset to the last 10 elements. The form along with the ribbits are then rendered to the template. Let's create
ribbit/templates/public.html for this view
{% Ribbits</h1> {% for ribbit in ribbits %} <div class="ribbitWrapper"> <img class="avatar" src="{{ ribbit.user.profile.gravatar_url }}"> <span class="name">{{ ribbit.user.first_name }}</span>@{{ ribbit.user.username }} <span class="time">{{ ribbit.creation_date|timesince }}</span> <p>{{ ribbit.content }}</p> </div> {% endfor %} </div> {% endblock %}
While looping over the ribbit objects, the template uses the
timesince template tag to automatically determine the time difference between the ribbit creation date and current time, and prints it in a Twitter-like way.
Ensuring that the development server is running, create a new ribbit and have a look at the Public Ribbits page to ensure everything is fine.
Let's commit the changes before proceeding:
git add . git commit -m 'Implemented Ribbit Submission and Public Ribbits Views'
Step 7 - User Profiles and Following Users
A twitter clone, User Profiles and Following Users go hand in hand. Let's write the routes for implementing this functionality. Update
ribbit/urls.py with the following code: url(r'^users/$', 'ribbit_app.views.users'), url(r'^users/(?P<username>\w{0,30})/$', 'ribbit_app.views.users'), url(r'^follow$', 'ribbit_app.views.follow'), )
An interesting route above is the one to direct to a specific user's profile.
<?P<username> captures the username queried via GET, and
\w{0,30} asserts that the maximum length for a username is 30 characters:
Next, we'll proceed with writing the view to render User Profiles. Append the following in `ribbit_app/views.py'.
from django.db.models import Count from django.http import Http404 def get_latest(user): try: return user.ribbit_set.order_by('-id')[0] except IndexError: return "" @login_required def users(request, username="", ribbit_form=None): if username: # Show a profile try: user = User.objects.get(username=username) except User.DoesNotExist: raise Http404 ribbits = Ribbit.objects.filter(user=user.id) if username == request.user.username or request.user.profile.follows.filter(user__username=username): # Self Profile or buddies' profile return render(request, 'user.html', {'user': user, 'ribbits': ribbits, }) return render(request, 'user.html', {'user': user, 'ribbits': ribbits, 'follow': True, }) users = User.objects.all().annotate(ribbit_count=Count('ribbit')) ribbits = map(get_latest, users) obj = zip(users, ribbits) ribbit_form = ribbit_form or RibbitForm() return render(request, 'profiles.html', {'obj': obj, 'next_url': '/users/', 'ribbit_form': ribbit_form, 'username': request.user.username, })
This view is perhaps the most interesting of all that we've covered so far. We start by ensuring that only logged in users are able to view profiles. In the routes we defined in
ribbit/urls.py, we wrote one to capture the username. This captured parameter is automatically called along with the request object in the users view. We come across two options for this view:
- A username is passed to the url to render a specific user's profile
- No username is passed which implies the user wants to view all profiles
We begin by checking if a username is passed and is not empty. Then, we try to fetch a User object for the corresponding username. Note the use of a try catch block in the code above. We simply raise a Http404 exception provided by Django to redirect to the default 404 template. Next, we need to check if the profile requested is of the logged in user or one of his buddies. If so, we don't need to render a follow link in the profile since the relation is already established. Otherwise, we pass along the
follow parameter in the view to print the Follow link.
Moving on to the second point, if no username is given in the url, we fetch a list of all the users and use the
annotate() function to add a
ribbit_count attribute to all objects, which stores the number of Ribbits made by each user in the queryset. This allows us to use something along the lines of
<user_object>.ribbit_count to fetch the Ribbit Count of the user.
Getting the latest Ribbit by each user is a bit tricky. We use Python's built in
map() function for this and call
get_latest() to all the elements of users queryset. The
get_latest() function is defined in the code above and makes use of a backward relation on the User<-->Ribbit relation. For instance
user.ribbit_set.all() would return all the ribbits by the user. We order the ribbits by id in descending order and slice the first element. The code is enclosed in a try catch block to catch the exception if no ribbits are created by the user. We're then making use of Python's
zip() function to link up each element of both iterators (users and ribbits) so that we have a tuple with User Object and Latest Ribbit pair. We then pass along this zipped object along with the forms to the template. Let's write our last view that will accept the request to follow a user
from django.core.exceptions import ObjectDoesNotExist @login_required def follow(request): if request.method == "POST": follow_id = request.POST.get('follow', False) if follow_id: try: user = User.objects.get(id=follow_id) request.user.profile.follows.add(user.profile) except ObjectDoesNotExist: return redirect('/users/') return redirect('/users/')
In the view above, we get the value of the
follow parameter, passed by POST. If the id is set we check if a user exists and add the relation, else, we catch an
ObjectDoesNotExist exception and redirect the user to the page that lists all User Profiles.
We're done with the views here. Let's write the remaining two templates required to render the user profiles. Open your text editor and edit
ribbit/templates/profiles.html.
{% Profiles</h1> {% for user, ribbit in obj %} <div class="ribbitWrapper"> <a href="/users/{{ user.username }}"> <img class="avatar" src="{{ user.profile.gravatar_url }}"> <span class="name">{{ user.first_name }}</span> </a> @{{ user.username }} <p> {{ user.ribbit_count}} Ribbits <span class="spacing">{{ user.profile.followed_by.count }} Followers</span> <span class="spacing">{{ user.profile.follows.count }} Following</span> </p> <p>{{ ribbit.content }}</p> </div> {% endfor %} </div> {% endblock %}
To list the user along with his last ribbit, we use a common python construct to iterate over a list of tuples:
for user, ribbit in obj. Inside the loop we print the information about the user along with his ribbit stats. Notice the use of a backward relation in
{{ user.profile.followed_by.count }}.
followed_by is the related name we set up while defining the ManyToManyField attribute for the UserProfile Model.
Finally, let's write the template to list a specific user's profile. Write the following code in
ribbit/templates/user.html.
{% extends "base.html" %} {% block login %} {% with user.username as username %} {{ block.super }} {% endwith %} {% endblock %} {% block content %} <div class="panel left"> <h1>{{ user.first_name }}'s Profile</h1> <div class="ribbitWrapper"> <a href="/users/{{ user.username }}"> <img class="avatar" src="{{ user.profile.gravatar_url }}"> <span class="name">{{ user.first_name }}</span> </a> @{{ user.username }} <p> {{ ribbits.count }} Ribbits <span class="spacing">{{ user.profile.follows.all.count }} Following</span> <span class="spacing">{{ user.profile.followed_by.all.count }} Followers</span> </p> {% if follow %} <form action="/follow" method="post"> {% csrf_token %} <input type="hidden" name="follow" value="{{ user.id }}"> <input type="submit" value="Follow"> </form> {% endif %} </div> </div> <div class="panel left"> <h1>{{ user.first_name }}'s Ribbits</h1> {% for ribbit in ribbits %} <div class="ribbitWrapper"> <a href="/users/{{ user.username }}"> <img class="avatar" src="{{ user.profile.gravatar_url }}"> <span class="name">{{ ribbit.user.first_name }}</span> </a> @{{ ribbit.user.username }} <span class="time">{{ ribbit.creation_date|timesince }}</span> <p>{{ ribbit.content }}</p> </div> {% endfor %} </div> {% endblock %}
As in the
buddies.html template, we pass the username of the logged in template to the parent template using the
{% with %} construct. Next, we display the user's profile and display the follow link only if the
follow variable is set to
True. After that, we list all the ribbits created by the user by iterating over the ribbits variable.
We're finally done with all the views and templates. Browse around all the links and try following dummy users and explore the Twitter-clone you've just created.
Let's commit our changes:
git add . git commit -m 'Implemented User Profiles and Following Relation on frontend'
Step 8 - Deployment to Heroku
I prefer to keep my development and production branches separate; git makes branching a breeze. Fire up the terminal and execute the following:
git branch -b production
This will create the production branch and switch to it immediately. Let's update our
.gitignore file and add the database to it. It's contents should be
*.pyc ribbit/database.db
Let's install some packages to our virtualenv that are required for deployment.
pip install psycopg2 dj-database-url gunicorn
We'll also create a file with all dependencies of the project so that they're picked up by Heroku.
pip freeze > requirements.txt
Next, let's edit
ribbit/settings.py. The database settings should be changed like.
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', # Add 'postgresql_psycopg2', 'mysql', 'sqlite3' or 'oracle'. 'NAME': 'ribbit', # Or path to database file if using sqlite3. 'USER': 'username', # Not used with sqlite3. 'PASSWORD': 'password', # Not used with sqlite3. 'HOST': '', # Set to empty string for localhost. Not used with sqlite3. 'PORT': '', # Set to empty string for default. Not used with sqlite3. } }
At the end of the file, append the following so that Heroku can figure out the database settings.
import dj_database_url DATABASES['default'] = dj_database_url.config()
Let's create a Procfile to start the process on Heroku's server. Place the following in a file, named
Procfile.
web: gunicorn ribbit.wsgi
Also, if your application isn't large scale, you can skip using storage services by appending the route for static files in
ribbit/urls.py
urlpatterns += patterns('django.contrib.staticfiles.views', url(r'^static/(?P<path>.*)$', 'serve'), )
We're all set! Let's commit the changes:
git commit -a -m 'Configured for Production'
Finally, we'll create a Heroku app and push our repo to the remote repository:
heroku create git push heroku production:master
Once the files are transferred, run
syncdb and apply the migrations to the database.
heroku run python manage.py syncdb heroku run python manage.py migrate ribbit_app
Finally, open the deployed app with:
heroku open
Conclusion
We're finally done with Ribbit in Django! This tutorial was quite long, indeed, and the application still has much more potential that can be implemented. I hope that, if you are new to Django, this article has encouraged you to dig more deeply.
Feel free to play along with my deployment at Heroku. If you have any questions, I'd be glad to answer and all questions.
Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this postPowered by
| http://code.tutsplus.com/tutorials/building-ribbit-in-django--net-29957 | CC-MAIN-2015-35 | refinedweb | 5,383 | 51.24 |
Member since 06-17-2017
3
1
Kudos Received
0
Solutions
09-04-2018 03:30 PM
09-04-2018 03:30 PM
The following is the description as per my knowledge. Kindly help me improvise the same. Steps before the patch is pushed Note : The following checks are not mandatory and can be skipped if the administrator confirms. "hdfs" is used to represent the HDFS Service user. If you are using another name for your Service users, you need to substitute your Service user name in each of the su commands. Important : If you have a secure server, you need Kerberos credentials for hdfs user access. i) Verify the HDFS file system health : su -hdfs -c "hdfs fsck / -files -blocks -locations > dfs-new-fsck-1.log" You should see the feedback that the filesystem under path “ / “ is HEALTHY ii) Run hdfs namespace and report : a. List directories - su -hdfs -c "hdfs dfs -ls -R / > dfs-new-lsr-1.log" b. Open the dfs-new-lsr-l.log and confirm that you can see the file and directory listing in the namespace. c. Run report command to create a list of DataNodes in the cluster. su -hdfs -c "hdfs dfsadmin -report > dfs-new-report-1.log" d. Open the dfs-new-report file and validate the admin report. iii) Note : You must do this comparison manually to catch all errors iv) From the NameNode WebUI, determine if all DataNodes are up and running. http://<namenode>:<namenodeport>; v) If you are on a highly available HDFS cluster, go to the StandbyNameNode web UI to see if all DataNodes are up and running: http://<standbynamenode>:<namenodeport>; vi) Verify that hdfs has read and write permissions. hdfs dfs -put [input file] [output file] hdfs dfs -cat [output file] 2. Make sure to fix all corrupt blocks/missing blocks/under replicated blocks in the cluster before proceeding. All blocks should have healthy replicas. hdfs fsck / If there are any corrupt/missing blocks/under replicated blocks : su -hdfs The following can be executed as a script : hdfs fsck / | grep 'Under replicated' | awk -F':' '{print $1}' >> /tmp/under_replicated_files for hdfsfile in cat /tmp/under_replicated_files; do echo "Fixing $hdfsfile :" ; hadoop fs -setrep 3 $hdfsfile; done 3.Version Checks and Memory availability has to be noted before rolling the patch : i) Java version ii) Python version ( 2.7.x ) iii) OpenSSL version ( v1.01, build 16 or later ) iv) other software requirements - scp , curl , tar , unzip , wget , yum , rpm v)Check for available memory on all masters and workers : free -m Sequence Of Actions : 1. Stop all third party softwares. 2. Stop the postgresql and mysql.( in case external database service is being used ) 3. Stop all services from the ambari UI. 4. Stop ambari agent on all nodes. ambari-agent stop 5. Stop ambari server service as well. ambari-server stop 6. The patch can be deployed now. 7. Start all third party services. 8. Start the postgresql and mysql. ( in case external database service is being used ) 9. Start ambari Server service. sudo su ambari-server status ambari-server start 10. Start ambari agent on all nodes. ambari-agent status ambari-agent stop 11. Start all services from the ambari UI. Note : There are no potential chances or any vulnerabilities of data loss in the cluster during patching. ... View more
@karthik nedunchezhiyan A simplified explanation of the process : Whenever a NN HA is achieved, there will be two NNs , One Active NN and other Standby NN, 1) DataNodes will send heartbeats to both NNs , so both Active and Standby will know where the blocks are placed. 2) Journal Nodes maintain the Shared edits , Whenever there is a write operation the JNs will update the edits, not the Active or Standby NN. Once the edits are updated by JN, the Standby will update its FS Image. 3)So this way at any point in time both the Active and the Standby will have the same updated FS Image. 4)Zookeeper will be responsible for holding the lock for the Active NN. 5) There will be two Zookeeper Failover Controllers, which will be responsible for monitoring the health of the NNs. 6) Whenever the Zookeeper does not receive a communication from the Zookeeper FC, it will release the lock and this will be acquired by the other Zookeeper FC and the Standby NN will become the Active NN. ... View more
09-16-2017 03:08 AM
09-16-2017 03:08 AM | https://community.cloudera.com/t5/user/viewprofilepage/user-id/57172 | CC-MAIN-2020-34 | refinedweb | 744 | 65.62 |
Dr. Phillip M. Feldman wrote: > Actually, I've tried both of these, and I get (different) errors in both > cases: > > In [1]: from mymath import * > > In [2]: reload(mymath) > NameError: name 'mymath' is not defined > > In [3]: reload('mymath') > TypeError: reload() argument must be module > > Please don't top post :o) 1/ Do not use the 'from <module> import *' form, unless you don't have any other choice, it will set in your namespace an undefined number of symbols, you may get some name collisions which usually lead to very nasty bugs. import mymath reload(mymath) will do the trick. If you are of those lazy coders you can write import mymath as mm reload(mm) mm.aFunction() If you are using a few functions and don't what to prefix them with the module name you can also write import mymath from mymath import func1, func2, func3 # reload the functions reload(mymath) func1 = mymath.func1 func2 = mymath.func2 func3 = mymath.func3 JM | https://mail.python.org/pipermail/python-list/2009-August/547720.html | CC-MAIN-2018-05 | refinedweb | 163 | 63.02 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.