Can not understand how to do two processes (process 1 and 2) are implemented separately executable files and exchange messages. Something like (1.Hello 2.Hi 1.How are you ? ...).
The code below illustrates how the two threads exchanging messages from text files.
Necessary that instead of text files become executable files (.dis) that communicate with each other messages.
implement LThread;
include "sys.m";
include "bufio.m";
include "draw.m";
sys:Sys;
FD: import Sys;
stOut: ref Sys->FD;
bufio:Bufio;
Iobuf:import bufio;
LThread:module{
init: fn(nil: ref Draw->Context, nil: list of string);
process: fn(pName: string);
};
init(nil: ref Draw->Context, nil: list of string) {
sys=load Sys Sys->PATH;
bufio=load Bufio Bufio->PATH;
spawn process("processA.txt");
sys->sleep(10);
spawn process("processB.txt");
}
process(pName: string) {
file_buf:ref Iobuf;
file_buf = bufio->open(pName, sys->ORDWR);
temp_line:string;
temp_line=" ";
while (temp_line != nil){
temp_line=file_buf.gets('\n');
sys->sleep(200);
sys->print("%s \n",temp_line);
}
}
Perhaps with the help of modules, i do not know.
I found what I wanted. Its own interface has the type of a Command module, and that is the type of the things it executes.
On lines of exec, cmd is set to the first of the words in the argument list, and the string .dis is concatenated to it (to account for the fact that Limbo object program files are conventionally named using this suffix).
information was taken: "The Limbo Programming Language".
exec(ctx: ref Draw->Context, args: list of string){
c: Command;
cmd,file: string;
cmd = hd args;
file = cmd + ".dis";
c = load Command file;
if(c == nil)
c = load Command "/dis/"+file;
if(c == nil) {
sys->print("%s: not found\n", cmd);
return;
}
c->init(ctx, args);
}
Related
I just created this code to experiment with type, i will explain the problems later.
My Code:
package main
import (
"fmt"
"math/rand"
"time"
)
type Games struct {
game string
creator string
}
func main() {
videogames := []Games{
{"inFamous", "Sucker Punch Games"},
{"Halo", "343 Games"},
{"JustCause", "Eidos"},
}
rand.Seed(time.Now().UTC().UnixNano())
i := rand.Intn(len(videogames))
fmt.Print(videogames[i])
}
If I run this the result will be,
{inFamous,Sucker Punch Games}
Now what i want to do is separate the arrays so that the result will be,
Game = inFamous
Publisher = Sucker Punch Games
Also i need to remove the opening and closing brackets.
You need a stringer method to define how your object will be printed:
func (g Games) String() string {
return fmt.Sprintf("Game = %v, Creator = %v", g.game, g.creator)
}
Check out the Tour of Go
fmt.Print() does not allow you to specify the format, but will use the type default format.
Instead, use fmt.Printf(). This should do what you need:
fmt.Printf("Game = %s\nPublisher = %s", videogames[i].game, videogames[i].creator)
I would like to write a system groovy script which inspects the queued jobs in Jenkins, and extracts the build parameters (and build cause as a bonus) supplied as the job was scheduled. Ideas?
Specifically:
def q = Jenkins.instance.queue
q.items.each { println it.task.name }
retrieves the queued items. I can't for the life of me figure out where the build parameters live.
The closest I am getting is this:
def q = Jenkins.instance.queue
q.items.each {
println("${it.task.name}:")
it.task.properties.each { key, val ->
println(" ${key}=${val}")
}
}
This gets me this:
4.1.next-build-launcher:
com.sonyericsson.jenkins.plugins.bfa.model.ScannerJobProperty$ScannerJobPropertyDescriptor#b299407=com.sonyericsson.jenkins.plugins.bfa.model.ScannerJobProperty#5e04bfd7
com.chikli.hudson.plugin.naginator.NaginatorOptOutProperty$DescriptorImpl#40d04eaa=com.chikli.hudson.plugin.naginator.NaginatorOptOutProperty#16b308db
hudson.model.ParametersDefinitionProperty$DescriptorImpl#b744c43=hudson.mod el.ParametersDefinitionProperty#440a6d81
...
The params property of the queue element itself contains a string with the parameters in a property file format -- key=value with multiple parameters separated by newlines.
def q = Jenkins.instance.queue
q.items.each {
println("${it.task.name}:")
println("Parameters: ${it.params}")
}
yields:
dbacher params:
Parameters:
MyParameter=Hello world
BoolParameter=true
I'm no Groovy expert, but when exploring the Jenkins scripting interface, I've found the following functions to be very helpful:
def showProps(inst, prefix="Properties:") {
println prefix
for (prop in inst.properties) {
def pc = ""
if (prop.value != null) {
pc = prop.value.class
}
println(" $prop.key : $prop.value ($pc)")
}
}
def showMethods(inst, prefix="Methods:") {
println prefix
inst.metaClass.methods.name.unique().each {
println " $it"
}
}
The showProps function reveals that the queue element has another property named causes that you'll need to do some more decoding on:
causes : [hudson.model.Cause$UserIdCause#56af8f1c] (class java.util.Collections$UnmodifiableRandomAccessList)
This questions follows another question of mine.
I don't exactly get what is wrong with my attempt to convert res to a ListSociete in the following test code :
import (
"errors"
"fmt"
"github.com/jmcvetta/neoism"
)
type Societe struct {
Name string
}
type ListSociete []Societe
func loadListSociete(name string) (ListSociete, error) {
db, err := neoism.Connect("http://localhost:7474/db/data")
if err != nil {
return nil, err
}
res := []struct {
Name string `json:"a.name"`
}{}
cq := neoism.CypherQuery{
Statement: `
MATCH (a:Societe)
WHERE a.name = {name}
RETURN a.name
`,
Parameters: neoism.Props{"name": name},
Result: &res,
}
db.Cypher(&cq)
if len(res) == 0 {
return nil, errors.New("Page duz not exists")
}
r := res[0]
return ListSociete(res), nil
}
Is a []struct{Name string} different from a []struct{Name string json:"a.name" } ?
Or is a ListSociete different from a []struct{Name string} ?
Thanks.
You are currently dealing with two different types:
type Societe struct {
Name string
}
and the anonymous one:
struct {
Name string `json:"a.name"`
}
These two would be identical if it wasn't for the tag. The Go Specifications states (my emphasis):
Two struct types are identical if they have the same sequence of fields, and if
corresponding fields have the same names, and identical types, and identical tags.
Two anonymous fields are considered to have the same name. Lower-case field names
from different packages are always different.
So, you can't do a simple conversion between the two. Also, the fact that you are converting slices of the two types makes the conversion problematic. I can see two options for you:
Copy through iteration:
This is the safe and recommended solution, but it is also more verbose and slow.
ls := make(ListSociete, len(res))
for i := 0; i < len(res); i++ {
ls[i].Name = res[i].Name
}
return ls, nil
Unsafe conversion:
Since both types have the same underlying data structure, it is possible to do an unsafe conversion.
This might however blow up in your face later on. Be warned!
return *(*ListSociete)(unsafe.Pointer(&res)), nil
Playground Example: http://play.golang.org/p/lfk7qBp2Gb
So, after some tests, here's whats i found out :
A ListSociete defined as such...
type Societe struct {
Name string `json:"a.name"`
}
type ListSociete []Societe
is different from this :
type ListSociete []struct {
Name string `json:"a.name"`
}
This second solution works, whereas the first doesn't.
So I assume there really is no way to convert (directly without writing an explicit loop) between types with different tags ?
In that case, i'll definitely go with the loop, as using tags directly in types (cf. second solution above) would make my code unreadable and unreusable, also I really have no clue what I would be messing with using the unsafe conversion method. So thanks for confirming different tags made different types.
I have a JAR file with following structure:
com
-- pack1
-- A.class
-- pack2
-- AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA.class
When I try to read, extract or rename pack2/AA...AA.class (which has a 262 byte long filename) both Linux and Windows say filename is too long. Renaming inside the JAR file doesn't also work.
Any ideas how to solve this issue and make the long class file readable?
This pages lists the usual limits of file systems: http://en.wikipedia.org/wiki/Comparison_of_file_systems
As you can see in the "Limits" section, almost no file system allows more than 255 characters.
Your only chance is to write a program that extracts the files and shortens file names which are too long. Java at least should be able to open the archive (try jar -tvf to list the content; if that works, truncating should work as well).
java.util.jar can handle it:
try {
JarFile jarFile = new JarFile("/path/to/target.jar");
Enumeration<JarEntry> jarEntries = jarFile.entries();
int i = 0;
while (jarEntries.hasMoreElements()) {
JarEntry jarEntry = jarEntries.nextElement();
System.out.println("processing entry: " + jarEntry.getName());
InputStream jarFileInputStream = jarFile.getInputStream(jarEntry);
OutputStream jarOutputStream = new FileOutputStream(new File("/tmp/test/test" + (i++) + ".class")); // give temporary name to class
while (jarFileInputStream.available() > 0) {
jarOutputStream.write(jarFileInputStream.read());
}
jarOutputStream.close();
jarFileInputStream.close();
}
} catch (IOException ex) {
Logger.getLogger(JARExtractor.class.getName()).log(Level.SEVERE, null, ex);
}
The output willbe test<n>.class for each class.
It is possible to get current line number by __LINE__ in Ruby or Perl.
For example:
print "filename: #{__FILE__}, line: #{__LINE__}"
Is there the same feature in Groovy?
Not directly, but you can get it through an Exception (or Throwable) stack trace. For example:
StackTraceElement getStackFrame(String debugMethodName) {
def ignorePackages = [
'sun.',
'java.lang',
'org.codehaus',
'groovy.lang'
]
StackTraceElement frame = null
Throwable t = new Throwable()
t.stackTrace.eachWithIndex { StackTraceElement stElement, int index ->
if (stElement.methodName.contains(debugMethodName)) {
int callerIndex = index + 1
while (t.stackTrace[callerIndex].isNativeMethod() ||
ignorePackages.any { String packageName ->
t.stackTrace[callerIndex].className.startsWith(packageName)
}) {
callerIndex++
}
frame = t.stackTrace[callerIndex]
return
}
}
frame
}
int getLineNumber() {
getStackFrame('getLineNumber')?.lineNumber ?: -1
}
String getFileName() {
getStackFrame('getFileName')?.fileName
}
String getMethodName() {
getStackFrame('getMethodName')?.methodName
}
def foo() {
println "looking at $fileName:$lineNumber ($methodName)"
}
foo()
// ==> looking at test.groovy:39 (foo)
A word of caution though: getting the line number, file name, or method like this is very slow.
I'm not an expert in Groovy, but I don't think so. I know that Java and C# don't have it.
The __LINE__ feature really started to help with debugging in C. C doesn't have exceptions or many of the other features modern languages have, but it did have macros that the compiler could expand anywhere in the code, which is why we needed __FILE__, __LINE__, etc to let us know where we were when something bad happened. This is how assert works in C and C++. The JVM has very good debugging tools, and combined with assert and exceptions, you can very easily pinpoint where something went wrong (stack traces are way better than just a line number anyway).
I believe the reason Ruby and Perl have those macros is because they were created by C hackers. I've never used either of those languages enough to know the level of debugging support or how useful the macros really are.